#include "yk_form_wzrk.h"
#include "ui_yk_form_wzrk.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QHeaderView>
#include <QSqlError>
#include "pub_var.h"
#include <QCompleter>

/*
com_printer_setting 表的使用。
p_type : 打印类别，入出库单。
p_item : 项目名称，
p_top， p_left，p_width，p_height 坐标定义

p_item_type 为 item，（p_top， p_left），（p_width，p_height）为区域左上角坐标和右下角坐标。
或者，p_width = p_height = 0， p_top， p_left为表格行，列值，可通过表格行列推算出对应坐标值。
top, left 为负值表示组合值，百位为起始，个位为终止。

p_item_type 为 base，
    p_item = 页面 ，p_width，p_height 定义页面大小。

    p_item = line_landscape，横线
    p_item = line_portrait，竖线
    （p_top， p_left），（p_width，p_height）为线段起始坐标和终止坐标。
    p_print_item 为以^隔开的步长列表，

p_font_name ： 字体名称
p_font_size ： 字体大小，单位mm
p_position ： 对齐方式 0:左，1:中，2:右,
p_mode ：打印模式：1, p_print_item + 项目内容; 0, 只打印项目内容
p_print_item ：与打印模式相关。
p_item_type ： 项目类型， item 内容项目，base 基础项目

*/

const int MAX_LINES = 8;    //单据最大项目数量

Form_yk_wzrk::Form_yk_wzrk(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_yk_wzrk)
{
    ui->setupUi(this);

    initialFinished = false;

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/yk_wzrk").toRect();
    this->setGeometry(rct);
    ui->pb_unlock_status_out->setEnabled(false);
    ui->pb_status_unlock_in->setEnabled(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrmt = new QSqlQuery(pub::db_m);
    qrmp = new QSqlQuery(pub::db_m);
    qrot = new QSqlQuery(pub::db_o);

    md = new QSqlQueryModel();
    mdrd = new QSqlQueryModel();
    mdrs = new QSqlQueryModel();
    mdcd = new QSqlQueryModel();
    mdcs = new QSqlQueryModel();
    md_dict = new QSqlQueryModel();

    sq = "SELECT CLASS3_NAME, CLASS3_CODE,CLASS2_CODE "
         " from COM_PRIV_CLASS3 where mark = '1'"
         " and CLASS2_CODE = '0510' order by CLASS3_CODE";
    qDebug()<<"提取入库操作类别："<<sq;
    mode_code_r = pub::fillCombo(ui->cbbMode_r, sq, -1, qro);

    sq = "SELECT CLASS3_NAME, CLASS3_CODE,CLASS2_CODE "
         " from COM_PRIV_CLASS3 where mark = '1' "
         " and CLASS2_CODE = '0520' order by CLASS3_CODE";
    qDebug()<<"提取出库操作类别："<<sq;
    mode_code_c = pub::fillCombo(ui->cbbMode_c, sq, -1, qro);

    //入出库临时表
    sq = "create temporary table if not exists tmp_mat_input (";
    sq += "atinc int auto_increment not null key, ";  //流水编码
    sq += "item_code VARCHAR(12) not null  , ";  //物资项目编码  unique
    sq += "item_name VARCHAR(100) not null,";          //品名
    sq += "company_code varchar(10) not null, ";      //生产商代码
    sq += "company_name varchar(64) not null, ";      //生产商名称
    sq += "specs varchar(50) not null,";               //规格
    sq += "approve_info VARCHAR(20) not null, "; //批准文号
    sq += "pack_qty varchar(10) not null , ";   //包装数量  decimal(10)
    sq += "pack_unit VARCHAR(12) not null , ";   //包装单位
    sq += "drug_type VARCHAR(5) not null , ";   //物资项目类别，中药，西药
    sq += "drug_quality VARCHAR(5) not null , ";   //物资项目类别，普药，特药
    sq += "sale_price varchar(20) not null , ";   //零售价格 decimal(12,2)
    sq += "in_price varchar(20) not null, ";   //采购价格 decimal(12,2)
    sq += "batch_no varchar(15), ";   //批号
    sq += "produce_date varchar(10), ";   //生产日期
    sq += "valid_date varchar(10), ";   //效期
    sq += "num varchar(10), ";   //出入数量
    sq += "invo_no varchar(25), ";   //发票号
    sq += "invo_date varchar(10), ";   //发票日期
    sq += "memo varchar(255), ";   //备注
    sq += "purchase_cost decimal(12,2) ,";   //购入金额
    sq += "retail_cost decimal(12,2) ,";   //零售金额
    sq += "min_unit varchar(10), ";   //最小单位
    sq += "group_code varchar(6),"; //组，发票入库的 in_no
    sq += "out_bill_code varchar(12),"; //出库单号
    sq += "out_serial_code varchar(6),"; //出库单序号
    sq += "out_list_code varchar(16),"; //出库单号
    sq += "med_list_codg varchar(45),";   //医保码
    sq += "stock_no varchar(20),";   //库存代码
    sq += "input_check_no varchar(15),"; //入库验收码
    sq += "num_before varchar(10) ";   //入出前数量
    sq += ")";

    qDebug()<<"create temporary table :"<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note",qrm->lastError().text());
        return;
    }
    //增加临时表索引
    qrm->exec("alter table tmp_mat_input "
              " add unique index prim_key (item_code,batch_no,group_code )");

    qrm->exec("delete from tmp_mat_input");
    showList();

    ui->tabWidget->setCurrentIndex(0);  //入库    

    //报表使用收款打印机
    QString printerName = setIni.value("sk/printer").toString();

    //配置打印机
    prt= new QPrinter(QPrinter::HighResolution);
    prt->setPrinterName(printerName);

    //发票纸张大小设定
    qrm->exec("select p_width,p_height,p_item from com_printer_setting where "
              " p_item_type = 'base' and p_type = '入出库单' and p_item in('偏移', '页面','单元缩进')");
    double w = 0, h = 0;
    xPos = yPos = 0;

    while(qrm->next())
    {
        QString itm = qrm->value(2).toString() ;

        if( itm == "页面")
        {
            w = qrm->value(0).toDouble();
            h = qrm->value(1).toDouble();
        }
        else if(itm == "偏移")
        {
            xPos = qrm->value(0).toDouble();
            yPos = qrm->value(1).toDouble();
        }
        else if(itm == "单元缩进")
        {
            margin = qrm->value(0).toDouble();
        }
    }

    QSizeF sz = QSizeF(w,h);
    QPageSize psz(sz,QPageSize::Millimeter,"",QPageSize::FuzzyMatch);
    prt->setPageSize(psz);

    QPageLayout pglot = QPageLayout(prt->pageLayout());

    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4 ;

    prt->setOrientation(QPrinter::Portrait);      //Portrait 纵向, Landscape 横向
    prt->setFullPage(true);
    pnt = new QPainter();

    //单据打印相关
    ui->deBegin->setDate(QDate::currentDate());
    ui->deEnd->setDate(QDate::currentDate());
    md_p_in = new QSqlQueryModel(); //入
    md_p_out = new QSqlQueryModel(); //出
    md_p_brw = new QSqlQueryModel();  //浏览

    //项目维护相关

    sq = "select company_name, company_code from mat_com_company where COMPANY_TYPE = '0' and VALID_FLAG = '1' order by company_name";
    qDebug()<<"提取生产厂家："<<sq;

    QStringList itemList;
    qro->exec(sq);
    while(qro->next())
    {
        itemList << qro->value(0).toString();
        producer_codes.append(qro->value(0).toString() + "^" + qro->value(1).toString() + "^");
    }

    //QCompleter *comp = new QCompleter(itemList,ui->cbb_producer_code->model());// 自动补全实例的构建
    comp = new QCompleter(itemList,ui->cbb_producer_code->model());// 自动补全实例的构建

    comp->setFilterMode(Qt::MatchContains);    // 设置匹配模式，只要包含就显示
    comp->setCaseSensitivity(Qt::CaseInsensitive);    // 设置大小写区分，不区大小写
    comp->setCompletionMode(QCompleter::PopupCompletion);    // 设置向用户提供补全的方式
    ui->cbb_producer_code->setCompleter(comp);    // 装载补全实例

    sq = "select kind_name, kind_code from mat_com_kindinfo where valid_flag = '1'";
    qDebug()<<"提取系统类别："<<sq;
    mat_kind = pub::fillCombo(ui->cbb_mat_kind, sq , -1, qrot);//

    sq = " select name " //, code, sort_id
         " from com_dictionary  "
         " where type ='MAT_MINI_UNIT' and valid_state = '1'"
         " order by sort_id";
    qDebug()<<"提取最小单位："<<sq;
    min_units = pub::fillCombo(ui->cbb_min_unit, sq , -1, qrot);//

    sq = " select name " //, code, sort_id
         " from com_dictionary  "
         " where type ='MAT_MINI_UNIT' and valid_state = '1'"
         " order by sort_id";
    qDebug()<<"提取包装单位："<<sq;
    pack_units = pub::fillCombo(ui->cbb_pack_unit, sq , -1, qrot);//

    sq  = " select dept_name,dept_code "
          " from com_department "
          " where valid_state = '1'"
          " order by dept_type,dept_name";
    qDebug()<<"提取全部诊室："<<sq;

    //出库操作的接收单位
    drug_consume_depts = pub::fillCombo(ui->cbbReceiveDept, sq, -1, qrot);

qDebug()<<"全部诊室："<<drug_consume_depts;

    //属性定义需要的门诊科室
    pub::fillCombo(ui->cbb_dept_code, sq, -1, qrot);
    ui->cbb_dept_code->addItem("通用");

    //提取后勤科室
    sq  = " select dept_name,dept_code "
          " from com_department "
          " where valid_state = '1'"
          " and dept_type in ('L') "
          " order by dept_type,dept_name";//
    qro->exec(sq);
    qDebug()<<"提取物资库："<<sq;
    while(qro->next())
    {
        store_depts += qro->value(0).toString() + "^";
        store_depts += qro->value(1).toString() + "^";
    }

    //提取当前 操作人员有权限的科室
    sq = " select role_dept "
         " from com_privileges "
         " WHERE type = 'dept' and code = '" + pub::usr_code + "'";
    qDebug()<<"提取操作员有权限的库存单位："<<sq;
    qrmt->exec(sq);

    ui->cbbStoreDept->clear();

    while(qrmt->next())
    {
        QString tmp = qrmt->value(0).toString();

        if(store_depts.indexOf(tmp) > -1)
        {
            ui->cbbStoreDept->addItem(tmp);
        }
    }

    is_new_fac = false;

    initialFinished = true;
}

Form_yk_wzrk::~Form_yk_wzrk()
{
    delete qrm;
    delete qro;
    delete qrmt;
    delete qrmp;
    delete qrot;
    delete md;
    delete mdrd;
    delete mdrs;
    delete mdcd;
    delete mdcs;
    delete md_dict;
    delete md_p_in; //入
    delete md_p_out; //出
    delete md_p_brw;  //浏览

    delete pnt;
    delete prt;

    delete comp;

    delete ui;

}

void Form_yk_wzrk::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/yk_wzrk", QVariant(this->geometry()));
    //delete timer_fac_changed;
    emit destroyW( "yk_wzrk" );

}

void Form_yk_wzrk::on_pbExit_clicked()
{
    close();
}

void Form_yk_wzrk::on_pbFresh_clicked()
{
    //storage_code,
    QString sq;
    sq = "select company_code 公司编码, company_name 公司名称, "
         " decode (company_type, '0', '生产厂家' ,'1', '经销商') 类型,"
         " spell_code, valid_flag 在用, company_type "
         " from MAT_COM_COMPANY where 1 = 1 ";

    QString valid_flag = "'v'";

    if(ui->ckb_in_use->isChecked())
    {
        valid_flag += ",'1'";
    }

    if(ui->ckb_un_use->isChecked())
    {
        valid_flag += ",'0'";
    }
    sq += " and valid_flag in (" + valid_flag + ") ";

    QString company_type = "'company_type'";
    if(ui->ckb_factory->isChecked())
    {
        company_type += ", '0'";
    }

    if(ui->ckb_dealer->isChecked())
    {
        company_type += ", '1'";
    }

    sq += " and company_type in (" + company_type + ") ";

    sq += " and (SPELL_CODE like '%" + ui->le_key_com->text().trimmed().toUpper() ;
    sq += "%' or COMPANY_NAME like '%" + ui->le_key_com->text().trimmed() + "%' )";

    sq += " order by company_type, company_name  ";

    qDebug()<<"提取供应关系列表："<<sq;

    md->setQuery(sq, pub::db_o);

    ui->tvList->setModel(md);
    int width = ui->tvList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvList, "0.15^0.5^0.15^0^0.1", width, 10);

}

void Form_yk_wzrk::on_tvList_clicked(const QModelIndex &index)
{

    is_new_fac = false; //非新增
    ui->le_company_name->setReadOnly(true);
    ui->le_company_spell->setReadOnly(true);
    ui->rb_dealer->setEnabled(false);
    ui->rb_factory->setEnabled(false);

    ui->le_company_code->setText(index.siblingAtColumn(0).data(0).toString());
    ui->le_company_name->setText(index.siblingAtColumn(1).data(0).toString());
    ui->le_company_spell->setText(index.siblingAtColumn(3).data(0).toString());

    if(index.siblingAtColumn(4).data(0).toString() == "1")
    {
        ui->ckb_valid->setChecked(true);
    }else{
        ui->ckb_valid->setChecked(false);
    }

    if(index.siblingAtColumn(5).data(0).toString() == "1")
    {
        ui->rb_dealer->setChecked(true);
    }else{
        ui->rb_factory->setChecked(true);
    }

}

void Form_yk_wzrk::on_pbSave0_clicked()
{

    if(is_new_fac)
    {
        //新增

        if(ui->le_company_name->text().trimmed().isEmpty())
        {
            QMessageBox::warning(this, "注意", "公司名称不可以为空！");
            return;
        }

        if(!ui->rb_factory->isChecked() && !ui->rb_dealer->isChecked())
        {
            QMessageBox::warning(this, "注意", "生产厂家或经销商必须选择一项！");
            return;
        }

        QString type, valid;
        if(ui->rb_factory->isChecked())
        {
            type = "0";
        }else{
            type = "1";
        }

        if(ui->ckb_valid->isChecked())
        {
            valid = "1";
        }else{
            valid = "0";
        }

        sq = "insert into mat_com_company ("
             "company_code, company_name, "
             "spell_code, company_type, "
             "oper_code, oper_date, valid_flag"
             ") values(";
        sq += "'" + ui->le_company_code->text() + "',"; //编码
        sq += "'" + ui->le_company_name->text().trimmed() + "',"; //名称
        sq += "'" + ui->le_spell_code->text().trimmed().toUpper() + "',"; //拼音
        sq += "'" + type + "',"; // company type
        sq += "'" + pub::usr_code + "',"; //
        sq += "sysdate,"; //
        sq += "'" + valid + "'"; //
        sq += ")";

    }
    else
    {
        //修改
        sq = "update mat_com_company set ";

        sq += " valid_flag = " ;
        if(ui->ckb_valid->isChecked())
        {
            sq += "'1'";
        }else{
            sq += "'0'";
        }
        sq += " where company_code = '" + ui->le_company_code->text() + "'";
    }

    qDebug()<<"供应关系变更："<<sq;
    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "Sql语句错误！\n" + sq);
        return;
    }

    QMessageBox::information(this, "注意", "保存完成！" );
    ui->le_spell_code->clear();
    ui->le_company_code->clear();
    ui->le_company_name->clear();

    is_new_fac = false;

}

void Form_yk_wzrk::on_pbSearch_clicked()
{

    search_item(ui->leKey->text().trimmed(),    //检索关键字
                mdrs,                           // sqlmodel
                ui->tvSource_r,                 //显示列表
                ui->cbbMode_r->currentText());  //入库模式
}

void Form_yk_wzrk::on_pb_new_company_clicked()
{
    is_new_fac = true; //新增
    ui->le_company_name->setReadOnly(false);
    ui->le_company_spell->setReadOnly(false);
    ui->rb_dealer->setEnabled(true);
    ui->rb_factory->setEnabled(true);

    ui->le_company_name->clear();
    ui->le_company_spell->clear();

    sq = "select SEQ_MAT_COMPANYCODE.nextval from dual";
    qro->exec(sq);
    qro->next();

    ui->le_company_code->setText( qro->value(0).toString() );
}

void Form_yk_wzrk::on_leKey_returnPressed()
{
    on_pbSearch_clicked();
}

void Form_yk_wzrk::item_selected(const QModelIndex index)
{

    qDebug()<<"项目确认。。。\n";

    item_detail.clear();
    item_detail.insert("item_name", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("specs", index.siblingAtColumn(1).data().toString());   //规格
    item_detail.insert("fac_name", index.siblingAtColumn(2).data().toString());   //生产商
    item_detail.insert("approve_info", index.siblingAtColumn(3).data().toString());   //批准文号, 项目维护的 item_code

    if(index.siblingAtColumn(4).isValid())
    {
        item_detail.insert("pack_qty", index.siblingAtColumn(4).data().toString());   //包装数量
        item_detail.insert("pack_unit", index.siblingAtColumn(5).data().toString());   //包装单位
        item_detail.insert("sale_price", QString::number(index.siblingAtColumn(6).data().toDouble(),'f',2));   //零售价格
        item_detail.insert("in_price", QString::number(index.siblingAtColumn(7).data().toDouble(),'f',2));   //采购价格（物资项目基本信息表）
        item_detail.insert("item_code", index.siblingAtColumn(8).data().toString());   //物资项目编码
        item_detail.insert("fac_code", index.siblingAtColumn(9).data().toString());   //生产商
        item_detail.insert("min_unit", index.siblingAtColumn(10).data().toString());  //最小单位
        item_detail.insert("kind_code", index.siblingAtColumn(11).data().toString());  //类别编码
        item_detail.insert("stock_code", index.siblingAtColumn(12).data().toString());  //库存编码 ?in_no
        item_detail.insert("in_num", index.siblingAtColumn(13).data().toString());  //入库数量
    }

    if(index.siblingAtColumn(14).isValid())
    {
        item_detail.insert("batch_no", index.siblingAtColumn(14).data().toString());  //批号
        item_detail.insert("produce_date", index.siblingAtColumn(15).data().toDate().toString("yyyy-MM-dd"));  //生产日期
        item_detail.insert("valid_date", index.siblingAtColumn(16).data().toDate().toString("yyyy-MM-dd"));  //效期
        item_detail.insert("in_price_sto", QString::number(index.siblingAtColumn(17).data().toDouble(),'f',2));  //采购价格（库存表）
        item_detail.insert("in_out_no", index.siblingAtColumn(18).data().toString());  //（库存表唯一编码）
        item_detail.insert("store_sum", index.siblingAtColumn(19).data().toString());  //库存数量（库存表）
        item_detail.insert("stock_no", index.siblingAtColumn(20).data().toString());  //库存数量（库存表）
    }

    if(index.siblingAtColumn(20).isValid())
    {
        item_detail.insert("out_bill_code", index.siblingAtColumn(20).data().toString());  //行唯一
        item_detail.insert("out_list_code", index.siblingAtColumn(21).data().toString());  //页唯一
        item_detail.insert("out_serial_code", index.siblingAtColumn(22).data().toString());
    }
    else
    {
        item_detail.insert("out_bill_code", "0");  //行唯一
        item_detail.insert("out_list_code", "");  //页唯一
        item_detail.insert("out_serial_code", "0");
    }

    if(ui->tabWidget->currentIndex() == 0)   //入库
    {
        ui->lePzwh->setText(item_detail["approve_info"]);
        ui->leScs->setText(item_detail["fac_name"]);
        //ui->leLsjg->setText(item_detail["sale_price"]);
        ui->lePackQty->setText(item_detail["pack_qty"]);
        ui->lePackUnit->setText(item_detail["pack_unit"]);
        ui->lePh->setText("");
        ui->leScrq->setText("");
        ui->leXq->setText("");
        ui->leRksl->setText("");
        ui->leGrjg->setText(item_detail["in_price"]);
        ui->leGrje->setText("");
        //ui->leFph->setText("");
        //ui->leFprq->setText("");
        ui->leBz->setText("");
        int stsm = item_detail["store_sum"].toInt() / item_detail["pack_qty"].toInt();
        ui->leStoreSum->setText( QString::number(stsm) );

        if(ui->cbbMode_r->currentText() == "入库退库" )
        {
            ui->lePh->setText(item_detail["batch_no"]);
            ui->leScrq->setText(item_detail["produce_date"]);
            ui->leXq->setText(item_detail["valid_date"]);
            ui->leRksl->setText( QString::number(stsm) );
            ui->leGrjg->setText(item_detail["in_price_sto"]);
        }

        if(ui->cbbMode_r->currentText() == "发票入库")
        {
            ui->leRksl->setText(item_detail["in_num"]);
        }

    }

    if(ui->tabWidget->currentIndex() == 1)   //出库
    {
        ui->lePzwh_2->setText(item_detail["approve_info"]);
        ui->leScs_2->setText(item_detail["fac_name"]);
        ui->leLsjg_2->setText(item_detail["sale_price"]);

        //ui->lePackQty_2->setText(item_detail["pack_qty"]);
        //ui->lePackUnit_2->setText(item_detail["pack_unit"]);
        ui->lePackQty_2->setText(item_detail["pack_qty"]);
        ui->lePackUnit_2->setText(item_detail["pack_unit"]);

        ui->lePh_2->setText(item_detail["batch_no"]);
        ui->leScrq_2->setText(item_detail["produce_date"]);
        ui->leXq_2->setText(item_detail["valid_date"]);
        int stsm = item_detail["store_sum"].toInt() / item_detail["pack_qty"].toInt();
        ui->leStoreSum_2->setText( QString::number(stsm) );
        ui->leRksl_2->setText("");
        ui->leGrjg_2->setText(item_detail["in_price_sto"]);
        ui->leGrje_2->setText("");
        ui->leFph_2->setText("");
        ui->leFprq_2->setText("");
        ui->leBz_2->setText("");
    }

    if(ui->tabWidget->currentIndex() == 2)   //单据打印
    {

    }

    if(ui->tabWidget->currentIndex() == 3)   //项目维护
    {
        // [approve_info] 实际保存内容为 [item_code]
        sq = "select * from mat_com_baseinfo where item_code = '"
                + item_detail["approve_info"] + "'";
        qro->exec(sq);
        qDebug()<<"select all fields : "<< sq;
        qro->next();

        ui->le_item_code->setText(qro->value("item_code").toString());// '物资项目编码';
        ui->le_item_name->setText(qro->value("item_name").toString());// '商品名称';
        ui->le_spell_code->setText(qro->value("spell_code").toString());// '商品名拼音码';
        ui->le_specs->setText(qro->value("specs").toString());// '规格';
        ui->le_sale_price->setText(QString::number(qro->value("sale_price").toDouble(), 'f', 2));// '参考零售价';
        ui->le_in_price->setText(QString::number(qro->value("in_price").toDouble(), 'f', 2));// '最新购入价';
        ui->le_pack_qty->setText(qro->value("pack_qty").toString());// '包装数';
        ui->le_approve_info->setText(qro->value("approve_info").toString());// '批文信息';

        ui->cbb_producer_code->setCurrentText(item_detail["fac_name"]); //  '生产厂家';

        QString tmp;

        // '包装单位';
        tmp = qro->value("pack_unit").toString();
        if(ui->cbb_pack_unit->findText( tmp, Qt::MatchExactly) < 0)
        {
            ui->cbb_pack_unit->setCurrentIndex(-1);
        }
        else
        {
            ui->cbb_pack_unit->setCurrentText(tmp);
        }

        //物资类别
        tmp = qro->value("kind_code").toString();
        qrot->exec("SELECT kind_name FROM mat_com_kindinfo "
                   " where valid_flag = '1' and kind_code = '" + tmp + "'");
        qrot->next();
        tmp = qrot->value(0).toString();
        ui->cbb_mat_kind->setCurrentText(tmp);

        // '最小单位';
        tmp = qro->value("min_unit").toString();
        if(ui->cbb_min_unit->findText( tmp, Qt::MatchExactly) < 0)
        {
            ui->cbb_min_unit->setCurrentIndex(-1);
        }
        else
        {
            ui->cbb_min_unit->setCurrentText(tmp);
        }

        // '主要使用科室';
        tmp = qro->value("effect_dept").toString();

        if(tmp == "0")
        {
            tmp = "通用";
        }
        else
        {
            qrot->exec("select dept_name from com_department where "
                       " valid_state = '1' and dept_code = '" + tmp + "'");
            qrot->next();
            tmp = qrot->value(0).toString();
        }

        if(tmp == "")
        {
            ui->cbb_dept_code->setCurrentIndex(-1);//  '统计关联科室，物资项目主要使用科室';
        }
        else
        {
            ui->cbb_dept_code->setCurrentText(tmp);//  '统计关联科室，物资项目主要使用科室';
        }

        // '有效状态';
        if(qro->value("valid_flag").toString() == "1")
        {
            ui->rb_inuse_baseinfo->setChecked(true);
        }
        else
        {
            ui->rb_unuse_baseinfo->setChecked(true);
        }
    }
}

void Form_yk_wzrk::on_tvSource_r_clicked(const QModelIndex &index)
{
    item_selected(index);
}

void Form_yk_wzrk::on_tvSource_r_doubleClicked(const QModelIndex &index)
{
    on_tvSource_r_clicked(index);
}

void Form_yk_wzrk::on_leRksl_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_wzrk::on_leGrjg_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_wzrk::calc_amount()
{
    if(!initialFinished)
    {
        return;
    }

    int in_num;
    double price;
    double tax;

    bool oki = false;   //入库转换
    bool okd = false;   //出库转换
    bool okt = false;   //税率转换

    if(ui->tabWidget->currentIndex() == 0)  //入库
    {
        in_num = ui->leRksl->text().toInt(&oki);
        price =  ui->leGrjg->text().toDouble(&okd);
        tax = ui->leTax->text().toDouble(&okt);

        if(oki && okd)
        {
            ui->leGrje->setText(QString::number(in_num * price, 'f', 2));
        }

        if(okt)
        {
            tax = tax / 100;    //
            ui->leTaxCost->setText(QString::number((in_num * price / (tax + 1 )) * tax , 'f', 2));  //税额
        }
    }

    if(ui->tabWidget->currentIndex() == 1)  //出库
    {
        in_num = ui->leRksl_2->text().toInt(&oki);
        price =  ui->leGrjg_2->text().toDouble(&okd);

        if(oki && okd)
        {
            ui->leGrje_2->setText(QString::number(in_num * price, 'f', 2));
        }
    }

}

void Form_yk_wzrk::on_pbAdd_clicked()
{

    if(!checkStatus("input_add_item"))
    {
        return;
    }

    //入库数据插入临时表
    sq = "replace into tmp_mat_input ("
         "item_code, item_name, company_code, "
         "company_name, specs, approve_info, ";  //物资项目编码,品名,生产商,规格,批准文号
    sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,物资项目中药西药类别
    sq += "drug_quality, sale_price, in_price,";   //物资项目类别，零售价格,采购价格
    sq += "med_list_codg,"; //存储 in_no , 发票入库用
    sq += "batch_no, produce_date, valid_date, num,";   //批号,生产日期,效期,数量
    sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost ,";   //发票号, 发票日期, 备注， 购入金额，零售金额
    sq += "out_bill_code, out_list_code, "
          " out_serial_code, group_code, num_before";//
    sq += ") values(";
    sq += "'" + item_detail["item_code"] + "',";//物资项目编码
    sq += "'" + item_detail["item_name"] + "',";//品名
    sq += "'" + item_detail["fac_code"] + "',";//生产商
    sq += "'" + item_detail["fac_name"] + "',";//生产商
    sq += "'" + item_detail["specs"] + "',";//规格
    sq += "'" + item_detail["approve_info"] + "',";//批准文号
    sq += "'" + item_detail["pack_qty"] + "',";//包装数量
    sq += "'" + item_detail["pack_unit"] + "',";//包装单位
    sq += "'" + item_detail["kind_code"] + "',";//物资项目类别，kind_code/drug_type
    sq += "'" + item_detail["drug_quality"] + "',";//物资项目类别，普药，特药
    sq += "'" + item_detail["sale_price"] + "',";//零售价格
    sq += "'" + ui->leGrjg->text().trimmed() + "',";//采购价格
    sq += "'" + item_detail["in_out_no"] + "',";//in_no, out_no
    sq += "'" + ui->lePh->text().trimmed() + "',";//批号
    sq += "'" + ui->leScrq->text().trimmed() + "',";//生产日期
    sq += "'" + ui->leXq->text().trimmed() + "',";//效期
    sq += "'" + QString::number(ui->leRksl->text().toInt() * item_detail["pack_qty"].toInt()) + "',";//数量
    sq += "'" + ui->leFph->text().trimmed() + "',";//发票号
    sq += "'" + ui->leFprq->text().trimmed() + "',";//发票日期
    sq += "'" + ui->leBz->text().trimmed() + "',";//备注
    sq += "'" + item_detail["min_unit"] + "',";//备注
    sq += ui->leGrje->text()+ ",";//购入金额
    sq += item_detail["sale_price"] + " * (" + ui->leRksl->text().trimmed() +")," ;//零售金额
    sq += "'" + item_detail["out_bill_code"] + "',";//
    sq += "'" + item_detail["out_list_code"] + "',";//
    sq += "'" + item_detail["out_serial_code"] + "',";//
    sq += "'" + item_detail["stock_code"] + "',";//
    sq += " 0 ";//
//    if(item_detail["stock_code"].isEmpty())
//    {
//        sq += "'" + item_detail["in_no"] + "'";//
//    }
//    else
//    {
//        sq += "'" + item_detail["stock_code"] + "'";//
//    }

    sq += ")";

    qDebug()<<"insert data to temporary table : "<< sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
        return ;
    }

    showList();

}

void Form_yk_wzrk::showList()
{

    qDebug()<<"刷新界面显示。。。\n";

    //计算合计金额
    sq = "select sum(purchase_cost) from tmp_mat_input";
    qrm->exec(sq);
    qrm->next();
    double amount = qrm->value(0).toDouble();

    qDebug()<<"合计金额："<<ui->leAmount->text();
    sq = " select item_name 物资项目名称, SPECS 规格, company_name 厂家, PACK_UNIT 包装单位, "
         " num / pack_qty 购入数量, purchase_cost 金额, item_code"
         " from tmp_mat_input order by atinc";

    qDebug()<<"待确认物资项目列表："<<sq;

    if(ui->tabWidget->currentIndex() == 0)
    {
        //入
        mdrd->setQuery(sq, pub::db_m);
        ui->tvDest_r->setModel(mdrd);
        int width = ui->tvDest_r->width();
        pub::setColumnWidth( ui->tvDest_r, "0.2^0.2^0.25^0.1^0.1^0.1^0^0^0^0^0^0^0", width, 20);
        ui->leAmount->setText(QString::number(amount, 'f', 2));
        ui->lePzwh->setText("");
        ui->leScs->setText("");
        //ui->leLsjg->setText("");
        ui->lePh->setText("");
        ui->leScrq->setText("");
        ui->leXq->setText("");
        ui->leRksl->setText("");
        ui->leGrjg->setText("");
        ui->leGrje->setText("");
        //ui->leFph->setText("");
        //ui->leFprq->setText("");
        ui->leBz->setText("");
        ui->lePackQty->setText("");

    }
    if(ui->tabWidget->currentIndex() == 1)
    {
        //出
        mdcd->setQuery(sq, pub::db_m);
        ui->tvDest_c->setModel(mdcd);
        int width = ui->tvDest_c->width();
        pub::setColumnWidth( ui->tvDest_c, "0.2^0.2^0.25^0.1^0.1^0.1^0^0^0^0^0^0^0", width, 20);
        ui->leAmount_2->setText(QString::number(amount, 'f', 2));
        ui->lePzwh_2->setText("");
        ui->leScs_2->setText("");
        ui->leLsjg_2->setText("");
        ui->lePh_2->setText("");
        ui->leScrq_2->setText("");
        ui->leXq_2->setText("");
        ui->leRksl_2->setText("");
        ui->leGrjg_2->setText("");
        ui->leGrje_2->setText("");
        ui->leFph_2->setText("");
        ui->leFprq_2->setText("");
        ui->leBz_2->setText("");
        ui->lePackQty_2->setText("");
        ui->leStoreSum_2->setText("");
    }

    ui->leKey->clear();
    ui->leKey_2->clear();
    ui->leKey_3->clear();

    item_detail.clear();

}

bool Form_yk_wzrk::checkStatus(QString mod)
{

    qDebug()<<"校验录入有效性。。。\n";

    QDate dt; //dt_m, dt_v,
    int testInt;
    double testDouble;
    bool convertValue;
    QString tmpStr;

    if(mod == "input_add_item")
    {
        //入库增加项目

        if(ui->leFprq->text().trimmed() != "--" )
        {
            dt = QDate::fromString(ui->leFprq->text(), "yyyy-MM-dd");
            if(!dt.isValid()){
                QMessageBox::warning(this, "注意", "发票日期录入无效！");
                return false;
            }
        }

        testInt = ui->leRksl->text().trimmed().toInt(&convertValue);
        if(testInt == 0)
        {
            QMessageBox::warning(this, "注意", "入库数量无效！");
            return false;
        }

        if(ui->cbbMode_r->currentText() == "入库退库")
        {
            if(testInt > ui->leStoreSum->text().toInt())
            {
                QMessageBox::warning(this, "注意", "退库数量不可以大于库存数量！");
                return false;
            }
        }


        testDouble = ui->leGrjg->text().trimmed().toDouble(&convertValue);
        if( qFuzzyCompare(testDouble, 0) || testDouble < 0)
        {
            QMessageBox::warning(this, "注意", "采购价格数值无效！");
            return false;
        }

        tmpStr = ui->leGrjg->text().trimmed();
        tmpStr = tmpStr.mid(tmpStr.indexOf("."));
        if( tmpStr.length() - 1 > 3 )
        {
            QMessageBox::warning(this, "注意", "采购价格数值小数位数超限！");
            return false;
        }

    }
    else if(mod == "input_save_invoice")
    {
        //入库单据保存
        if(ui->cbbStoreDept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择库存单位！");
            return false;
        }

        if(ui->cbbMode_r->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择入库模式！");
            return false;
        }

        if(ui->cbbCompany->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择入库供货商！");
            return false;
        }

        if(mdrd->rowCount()<1)
        {
            QMessageBox::warning(this, "注意", "未录入项目数据！");
            return false;
        }

        int sto_num = ui->leStoreSum_2->text().toInt();
        int oper_num = ui->leRksl_2->text().toInt();
        if(oper_num > sto_num)
        {
            QMessageBox::warning(this, "注意", "出库数量大于库存数量！");
            return false;
        }

    }
    else if(mod == "output_add_item")
    {
        //出库增加项目
        if(item_detail.size() == 0)
        {
            if(ui->lePzwh_2->text().isEmpty())
            {
                QMessageBox::warning(this, "注意", "未选定项目！");
                return false;
            }
        }

        testInt = ui->leRksl_2->text().trimmed().toInt(&convertValue);

        if(testInt == 0)
        {
            QMessageBox::warning(this, "注意", "出库数量数值无效！");
            return false;
        }

        if(ui->leStoreSum_2->text().toInt()  < testInt)
        {
            QMessageBox::warning(this, "注意", "出库数量不可以大于库存数量！");
            return false;
        }
    }
    else if(mod == "output_save_invoice")
    {
        //出库单据保存
        if(ui->cbbStoreDept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择库存单位！");
            return false;
        }

        if(ui->cbbMode_c->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择出库模式！");
            return false;
        }

        if(ui->cbbReceiveDept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择物资项目接收单位！");
            return false;
        }

        if(ui->cbbMode_c->currentText() != "报损"
                && ui->cbbMode_c->currentText() != "特殊出库" )
        {
            if( ui->cbbReceiveDept->currentText() == ui->cbbStoreDept->currentText() )
            {
                QMessageBox::warning(this, "注意", "物资项目接收单位与库存单位重复！");
                return false;
            }
        }
        else
        {
            if( ui->cbbReceiveDept->currentText() != ui->cbbStoreDept->currentText() )
            {
                QMessageBox::warning(this, "注意", "报损或特殊出库，物资项目接收单位必须与库存单位相同！");
                return false;
            }
        }

        if(mdcd->rowCount()<1)
        {
            QMessageBox::warning(this, "注意", "未录入项目数据！");
            return false;
        }
    }
    else
    {
        QMessageBox::warning(this, "注意", "校验模式选择无效！");
        return false;
    }
    return true;
}

void Form_yk_wzrk::on_pbSave_clicked()
{

    qDebug()<<"入库保存例程。。。\n";

    if(!checkStatus("input_save_invoice"))
    {
        return;
    }

    int pos;

    //入库类型, CLASS3_MEANING_CODE
    pos = pub::searchStr(mode_code_r, "^", ui->cbbMode_r->currentText());
    QString in_type = pub::getStr(mode_code_r, "^", pos + 1);
    QString class2_code = pub::getStr(mode_code_r, "^", pos + 2);

    //检索科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    //检索代货商代码
    pos = pub::searchStr(company_codes, "^", ui->cbbCompany->currentText()) + 1;
    QString company = pub::getStr(company_codes, "^", pos);

    //生成 in_list_code，入库单号
    QString in_list_code ;
    sq = " select max(in_list_code) from mat_com_input ";
    qDebug()<<"获取当前最大单据号:"<<sq;
    qro->exec(sq);
    qro->next();

    QString sn = QString::number(qro->value(0).toInt() + 1);

    //sn 长度, 此生绝无可能超过 10
    in_list_code = QString("0000000000").replace(10 - sn.length(), sn.length(), sn);

    //按临时表记录数生成 入库流水号，库存流水号，库存组编号，
    QStringList in_nos, stock_codes, stock_no;

    if(ui->cbbMode_r->currentText() == "一般入库"
            || ui->cbbMode_r->currentText() == "特殊入库"
            || ui->cbbMode_r->currentText() == "入库退库"
            )
    {
        //一般入库，需要生成
        sq = "select count(*) from tmp_mat_input ";
        qrm->exec(sq);
        qrm->next();
        int count = qrm->value(0).toInt();

        if( count < 1)
        {
            QMessageBox::warning(this, "注意", "临时表数据为空！");
            return ;
        }

        while(count > 0)
        {

            sq = "SELECT "
                 " SEQ_MAT_STOCKCODE.NEXTVAL, "
                 " SEQ_MAT_INNO.NEXTVAL,"
                 " SEQ_MAT_STOCKNO.NEXTVAL"
                 " FROM DUAL";
            qDebug()<<"生成 _code ："<<sq;

            if(qro->exec(sq))
            {
                qro->next();
                stock_codes << qro->value(0).toString();
                in_nos << qro->value(1).toString();
                stock_no << qro->value(2).toString();
            }
            else
            {
                QMessageBox::warning(this, "注意", "未能获取 group_code ！");
                return ;
            }

            count --;
        }

    }

    QSqlRecord rcd;
    QMap<QString, QString> para;

    para["dept_code"] = dept_code;  //库存单位
    para["io_type"] = in_type;   //入库类型
    para["class2_code"] = class2_code;   //
    para["company_code"] = company; //供货公司
    para["company_name"] = ui->cbbCompany->currentText(); //供货公司
    para["state"] = "2"; //0 申请， 1审批， 2核准
    para["in_out"] = "in"; //入，出

    if(ui->cbbMode_r->currentText() == "入库退库")
    {
        //退库进行负数计算
        para["mode"] = "-";
    }
    else
    {
        para["mode"] = "";
    }

    pub::db_o.transaction();
    QString tmpSql;
    QSqlQuery tmpQr;

    sq = "select * from tmp_mat_input ";
    qrm->exec(sq);

    int serial_int = 0; //入库单页内序号,
    int count = 0;

    while(qrm->next())
    {
        if(ui->cbbMode_r->currentText() == "发票入库")
        {
            //检索供货库房代码
            pos = pub::searchStr(store_depts, "^", ui->cbbCompany->currentText()) + 1;

            sq = "update mat_com_input "
                 " set invoice_no = '%1' ,"
                 " invoice_date = to_date('%2','yyyy-mm-dd')"
                 " WHERE stock_code = '%3' ";
            sq = sq.arg(qrm->value("invo_no").toString())
                    .arg(qrm->value("invo_date").toDate().toString("yyyy-MM-dd"))
                    .arg(qrm->value("group_code").toString());

            qDebug()<<"发票入库 : " << sq;
            pub::db_o.exec(sq);
            continue;
        }

        serial_int ++ ;//页面内部行号

        if(serial_int > MAX_LINES)
        {
            //每页限制行数
            serial_int = 1;

            QString sn = QString::number(in_list_code.toInt() + 1);
            in_list_code = QString("0000000000").replace(10 - sn.length(), sn.length(), sn);

        }

        para["list_code"] = in_list_code;   //入库单据号
        para["serial_code"] = QString::number(serial_int);   //

        para["stock_code"] = stock_codes[count];   //入库，para 与 rcd 一致。退库不一致
        para["in_no"] = in_nos[count];   //入库流水号
        para["stock_no"] = stock_no[count];   //库存流水号

        //临时表当前行数据
        rcd = qrm->record();
//        if(ui->cbbMode_r->currentText() == "入库退库"
//                || ui->cbbMode_r->currentText() == "核准入库")
//        {
//            //退库，核准入库，使用旧 group_code
//            //para["stock_no"] = rcd.value("group_code").toString();

//        }

        //保存 mat_com_input
        if(!ins_input(rcd, para))
        {
            pub::db_o.rollback();
            return;
        }

        //保存 mat_com_stockdetail
        if(!ins_storage(rcd, para))
        {
            pub::db_o.rollback();
            return;
        }

        count++;
    }

    pub::db_o.commit();
    qrm->exec("delete from tmp_mat_input");
    showList();
    change_lock_status("in", true);
}

bool Form_yk_wzrk::check_input(QSqlRecord rcd, QMap<QString,QString> pa, QString mode)
{
    //

    qDebug()<<"开始自动核准入库。。。\n";

    QSqlQuery qr(pub::db_o);

    int pos;

    //入库类型, CLASS3_MEANING_CODE
    //QString in_type = "05";   //物资管理

    QString in_type, class2_code;
    in_type = "05";   //物资管理
    class2_code = "0510"; //核准入库


    //供货科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString company_code = pub::getStr(store_depts, "^", pos);

    //收货科室代码
    pos = pub::searchStr(drug_consume_depts, "^", ui->cbbReceiveDept->currentText()) + 1;
    QString dept_code = pub::getStr(drug_consume_depts, "^", pos);

    if(mode == "back")
    {
        //退库
        QString tmp;

        if(pa["in_out"] == "out")
        {
            company_code = pa["dept_code"];
            dept_code = pa["receive_dept_code"];
        }
        else
        {
            tmp = company_code;
            company_code = dept_code;
            dept_code = tmp;
        }

    }

    //生成 in_list_code，入库单号
    QString in_list_code ;
    sq = " select max(in_list_code) from mat_com_input ";
    qDebug()<<"获取当前最大单据号:"<<sq;

    qr.exec(sq);
    qr.next();

    QString sn = QString::number(qr.value(0).toInt() + 1);

    //sn
    in_list_code = QString("0000000000").replace(10 - sn.length(), sn.length(), sn);

    QStringList in_nos, stock_codes, stock_no;

    sq = "SELECT "
         " SEQ_MAT_STOCKCODE.NEXTVAL, "
         " SEQ_MAT_INNO.NEXTVAL,"
         " SEQ_MAT_STOCKNO.NEXTVAL"
         " FROM DUAL";
    qDebug()<<"生成 _code ："<<sq;

    if(qr.exec(sq))
    {
        qr.next();
        stock_codes << qr.value(0).toString();
        in_nos << qr.value(1).toString();
        stock_no << qr.value(2).toString();
    }
    else
    {
        QMessageBox::warning(this, "注意", "未能获取 group_code ！");
        return false;
    }

    //QSqlRecord rcd;
    QMap<QString, QString> para = pa;

    para["dept_code"] = dept_code;  //库存单位
    para["io_type"] = in_type;   //入库类型
    para["class2_code"] = class2_code;   //
    para["company_code"] = company_code; //供货公司
    para["state"] = "2"; //0 申请， 1审批， 2核准
    para["in_out"] = "in"; //入，出

    if(mode == "out")
    {
        //出库
        para["company_name"] = ui->cbbStoreDept->currentText(); //供货公司
        para["mode"] = "";
    }
    else
    {
        //退库
        para["company_name"] = ui->cbbReceiveDept->currentText(); //供货公司
        para["mode"] = "-";
    }



    int serial_int = 0; //入库单页内序号,
    int count = 0;

    serial_int ++ ;//页面内部行号

    para["list_code"] = in_list_code;   //入库单据号
    para["serial_code"] = QString::number(serial_int);   //


    para["stock_code"] = stock_codes[count];   //入库，para 与 rcd 一致。退库不一致
    para["in_no"] = in_nos[count];   //入库流水号

    para["stock_no"] = rcd.value("stock_no").toString();   //库存流水号

    if(mode == "out")
    {
        //出库
//        para["stock_no"] = stock_no[count];   //库存流水号
        //
    }
    else
    {
        //退库
//       para["stock_no"] = rcd.value("stock_no").toString();   //库存流水号
        //para["stock_code"] = stock_codes[count];   //入库，para 与 rcd 一致。退库不一致
      }




    //保存 mat_com_input
    if(!ins_input(rcd, para))
    {
        return false;
    }

    //保存 mat_com_stockdetail
    if(!ins_storage(rcd, para))
    {
        return false;
    }

    return true;

}

bool Form_yk_wzrk::ins_storage(QSqlRecord rcd, QMap<QString,QString> para)
{

    qDebug()<<"库存表管理。。。\n";

    qDebug()<<"ins_storage para : "<<para<<"\n";

    if(para["in_out"] == "out")
    {
        //出库, 修改已经存在的记录
        sq = "UPDATE mat_com_stockdetail SET ";
        sq += " STORE_NUM = STORE_NUM - (" + para["mode"] + rcd.value("num").toString() + "),"; //库存数量
        sq += " STORE_COST  = STORE_COST - (" + para["mode"] + rcd.value("purchase_cost").toString() + "),"; // 库存金额
        //sq += " SERIAL_CODE = " + para["serial_code"] +","; // 序号
        //sq += " TARGET_DEPT = '" + para["receive_dept_code"]  + "',";  //最后变更源
        sq += " CLASS2_priv = '" + para["class2_code"] + "',";// 操作代码
        sq += " CLASS3_priv = '" + para["io_type"] + "',";// 操作代码
        sq += " OPER_CODE   = '" + pub::usr_code + "', ";//操作员
        sq += " OPER_DATE   = SYSDATE ";//日期
        sq += " WHERE STORAGE_CODE = '" + para["dept_code"] + "'"  ;//库存单位
        sq += " AND item_code  = '" + rcd.value("item_code").toString() + "'" ;  //物资项目编码
        //sq += " AND BATCH_NO = '" + rcd.value("batch_no").toString() + "'";  //批号"
        //sq += " AND stock_code = '" + rcd.value("group_code").toString() + "'" ; //批次号
        sq += " AND stock_no = '" + rcd.value("stock_no").toString() + "'" ; //库存编码

        qDebug()<<" UPDATE mat_com_stockdetail : "<<sq;
        pub::db_o.exec(sq);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 mat_com_stockdetail 错误！\n" + pub::db_o.lastError().text() );
            return false;
        }
        return true;
    }

    //检索mat_com_stockdetail 中是否存在记录，确定进行变更或者插入。
    //
    sq = " select item_code from mat_com_stockdetail where ";
    sq += " storage_code = '" + para["dept_code"] + "'";  //库存单位
    sq += " AND item_code  = '" + rcd.value("item_code").toString() + "'";   //物资项目编码
    if(ui->tabWidget->currentIndex() == 0)
    {
        //入库
        sq += " AND stock_code  = '" + rcd.value("group_code").toString() + "'";   //物资项目编码
    }
    else
    {
        //出库
        sq += " AND stock_no  = '" + rcd.value("stock_no").toString() + "'";   //物资项目编码

    }

    qDebug()<<"检索 mat_com_stockdetail : "<<sq;

    QSqlQuery tmpQr = pub::db_o.exec(sq);
    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "检索 mat_com_stockdetail 发生错误！\n" + pub::db_o.lastError().text() );
        qDebug()<<"检索 mat_com_stockdetail 发生错误 : " << pub::db_o.lastError().text();
        return false;
    }

    tmpQr.next();

    if(tmpQr.isNull(0))
    {
        //未找到旧数据，插入新记录
        sq = "INSERT INTO mat_com_stockdetail ("
             " stock_code, stock_no, storage_code, kind_code, "//
                " item_code, item_name,specs,  "//
                " batch_no,produce_date, valid_date, "//
                " store_num, store_cost, "//
                " min_unit, pack_unit, pack_qty, "
                " in_no, in_num, in_price, input_date,  "//
                " output_date, sale_price, sale_cost, "//
                " factory_code, company_code, "//
                " valid_state, oper_code, oper_date,"
                " CLASS2_priv ,CLASS3_priv "//
                " )  VALUES( ";

        //库存流水号(唯一)，库存序号（类似group_code）,库房编码，类别编码
        sq += "'" + para["stock_code"] + "',"  ;
        sq += "'" + para["stock_no"] + "',"  ;
        sq += "'" + para["dept_code"] + "',"  ;
        sq += "'" + rcd.value("drug_type").toString() + "',"  ;

        //物资项目编码，项目名称，规格
        sq += "'" + rcd.value("item_code").toString() + "',"  ;
        sq += "'" + rcd.value("item_name").toString() + "',"  ;
        sq += "'" + rcd.value("specs").toString() + "',"  ;

        //批号，生产日期，有效期
        sq += "'" + rcd.value("batch_no").toString() + "',"  ;

        if(rcd.value("produce_date").toString() == "--")//
        {
            sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
        }else{
            sq += "to_date('" + rcd.value("produce_date").toString() + "','yyyy-mm-dd')," ;
        }

        if(rcd.value("valid_date").toString() == "--")//
        {
            sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
        }else{
            sq += "to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd')," ;
        }

        //库存数量，金额
        sq += rcd.value("num").toString() + ","  ;
        sq += rcd.value("purchase_cost").toString() + ","  ;

        //最小单位，包装单位，每包装数量
        sq += "'" + rcd.value("min_unit").toString() + "',"  ;
        sq += "'" + rcd.value("pack_unit").toString() + "',"  ;
        sq += rcd.value("pack_qty").toString() + ","  ;

        //入库号，入库数量，入价格，入日期
        sq += "'" + para["in_no"] + "',";
        sq += rcd.value("num").toString() + ","  ;
        sq += rcd.value("in_price").toString() + ","  ;
        sq += " sysdate, "  ;

        //出日期，零售价格，零售金额
        sq += "to_date('0001-01-01','yyyy-mm-dd'),";
        sq += rcd.value("sale_price").toString() + ","  ;
        sq += rcd.value("retail_cost").toString() + ","  ;

        //生产商代码，供货商代码
        sq += "'" + rcd.value("company_code").toString() + "',"  ;
        sq += "'" + para["company_code"] + "',";

        //有效标志，操作员，操作日期
        sq += "'1',";
        sq += "'" + pub::usr_code + "' , ";
        sq += " SYSDATE,"  ;

        sq += "'" + para["class2_code"] + "',";// 操作代码
        sq += "'" + para["io_type"] + "'";// 操作代码

        sq += ")";

        qDebug()<<"mat_com_stockdetail 插入新记录 : "<<sq;

        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", " mat_com_stockdetail 插入新记录错误！\n" + pub::db_o.lastError().text() );
            qDebug()<<"mat_com_stockdetail 错误 : "<<pub::db_o.lastError().text();
            return false;
        }
    }
    else
    {
        //入库变更库存，库存记录非空，只能是退库。修改已经存在的记录,

        sq = "UPDATE mat_com_stockdetail SET ";
        sq += " STORE_NUM = STORE_NUM + ("
                + para["mode"] + rcd.value("num").toString() + "),"; //库存数量
        sq += " STORE_COST  = STORE_COST + ("
                + para["mode"] + rcd.value("purchase_cost").toString() + "),"; // 库存金额
        //sq += " return_num = " + rcd.value("num").toString() + ",";// 退库数量
        //sq += " return_in_no = " + para["serial_code"] + ","; // 退库关联in_no
        //sq += " TARGET_DEPT = '" + para["company"]  + "',";  //最后变更源
        sq += " CLASS2_priv = '" + para["class2_code"] + "',";// 操作代码
        sq += " CLASS3_priv = '" + para["io_type"] + "',";// 操作代码
        sq += " OPER_CODE   = '" + pub::usr_code + "', ";//操作员
        sq += " OPER_DATE   = SYSDATE ";//日期
        sq += " WHERE ";//STORAGE_CODE = '" + para["dept_code"] + "'"  ;//库存单位"

        //sq += " STOCK_CODE = '" + rcd.value("group_code").toString() + "'" ; //库存唯一编码

        if(ui->tabWidget->currentIndex() == 0)
        {
            //入库
            sq += " STOCK_CODE = '" + rcd.value("group_code").toString() + "'" ; //库存唯一编码
        }
        else
        {
            //出库
            sq += " storage_code = '" + para["dept_code"] + "'";  //库存单位
            sq += " AND item_code  = '" + rcd.value("item_code").toString() + "'";   //物资项目编码
            sq += " AND stock_no  = '" + rcd.value("stock_no").toString() + "'";   //物资项目编码
        }

        qDebug()<<" UPDATE mat_com_stockdetail : "<<sq;
        pub::db_o.exec(sq);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 mat_com_stockdetail 错误！\n" + pub::db_o.lastError().text() );
            return false;
        }

    }

    return true;

}

bool Form_yk_wzrk::ins_input(QSqlRecord rcd, QMap<QString, QString> para)
{

    qDebug()<<"入库记录表管理。。。\n";
    //QString tmpSql;
    //QSqlQuery tmpQr;

    sq = " INSERT INTO MAT_COM_INPUT ( ";
    sq += " in_no, in_list_code, in_serial_no,"; //入库流水号，入库单号，单据内流水号
    sq += " storage_code, stock_code, return_in_no, in_class3,"; //库房代码，库存流水号，退库关联，入库类别
    sq += " trans_type, in_state,"; //交易类别，入库状态
    sq += " item_code, item_name, kind_code,";//项目代码，项目名称，库存类别
    sq += " specs, batch_no,in_num,min_unit,";//规格，批号，入库数量，最小单位
    sq += " pack_in_num,pack_unit, pack_price,pack_qty,";//包装入库数量，包装单位，包装价格，每包数量
    sq += " in_price,in_cost,add_rate,sale_price,sale_cost,";//入价，入金额，价率，零售价，零售金额
    sq += " priv_store_num,in_date, apply_oper,apply_date,";//入前库存，入日期，申请操作员，申请日期
    sq += " exam_oper, exam_date, approve_oper, approve_date, ";//审核员，审核日期，核准员，核准日期
    sq += " invoice_no, invoice_date, source_dept, source_deptname,"; //发票号，发票日期，来源科室代码，名称
    sq += " company_code, company_name, factory_code,"; //供货公司代码，名称，生产商代码
    sq += " produce_date, valid_date,produce_flag,";//生产日期，有效期，生产标志
    sq += " out_no,finance_flag, return_num, ";//出库单号，财务标志，返回数量
    sq += " oper_code, oper_date, "
          " is_addstore,is_invoicein, memo";//操作员，操作日期，加库存标志 1，发票入标志0

    sq += " ) values (";

    //入库流水号 入库单据号 单据内流水号
    sq += "'" + para["in_no"] + "' ,";
    sq += "'" + para["list_code"] + "' ,";
    sq += "'" + para["serial_code"] + "' ,";

    //库房代码，库存流水号，入库类别
    sq += "'" + para["dept_code"] + "' ,";

    if(ui->cbbMode_r->currentText() == "入库退库")
    {
        //退库，使用旧 group_code
        sq += "'" + rcd.value("group_code").toString() + "' ,";
        sq += "'" + rcd.value("med_list_codg").toString() + "' ,";

        QString tmp_sql = "update MAT_COM_INPUT set return_num = return_num + " ;
        tmp_sql += rcd.value("num").toString() ;
        tmp_sql += " where ";
        tmp_sql += " in_no = '" + rcd.value("med_list_codg").toString() + "' ";

        qDebug()<<"变更退库关联信息："<<tmp_sql;

        pub::db_o.exec(tmp_sql);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 mat_com_input 错误！\n" + pub::db_o.lastError().text() );
            return false;
        }


    }
    else
    {
        sq += "'" + para["stock_code"] + "' ,";
        sq += "'', ";
    }


    sq += "'" + para["io_type"] + "' ,";

    //交易类别
    if(para["mode"] == "")
    {
        sq += "'1' ,";
    }
    else
    {
        sq += "'2' ,";
    }

    //入库状态, 直接设置核准状态
    sq += "'2' ,";

    //项目代码，项目名称，库存类别
    sq += "'" + rcd.value("item_code").toString() + "'," ; //-物资项目编码
    sq += "'" + rcd.value("item_name").toString() + "'," ; //-物资项目商品名
    sq += "'" + rcd.value("drug_type").toString() + "'," ; //-物资项目类别 drug_type/kind_code

    //规格，批号，入库数量，最小单位
    sq += "'" + rcd.value("specs").toString() + "'," ; //-规格
    sq += "'" + rcd.value("batch_no").toString() + "'," ; //批号
    sq += para["mode"] + rcd.value("num").toString() + ", " ; //-购入数量
    sq += "'" + rcd.value("min_unit").toString() + "'," ; //最小单位

    //包装入库数量，包装单位，包装价格，每包数量
    sq += para["mode"] + rcd.value("num").toString() + ", " ; //-购入数量
    sq += "'" + rcd.value("pack_unit").toString() + "'," ; //包装单位
    sq += rcd.value("in_price").toString() + ", " ; //-购入价
    sq += "'" + rcd.value("pack_qty").toString() + "'," ; //包装数

    //入价，入金额，价率，零售价，零售金额
    sq += rcd.value("in_price").toString() + ", " ; //-购入价
    sq += para["mode"] + rcd.value("purchase_cost").toString() + "," ; //-购入金额
    sq += "0,";
    sq += rcd.value("sale_price").toString() + "," ; //-零售价
    sq += para["mode"] + rcd.value("retail_cost").toString() + "," ; //-零售金额

    //入前库存，入日期，申请操作员，申请日期
    sq += "0, sysdate,'',sysdate,";

    //审核员，审核日期，核准员，核准日期
    sq += "'', sysdate,'',sysdate,";

    //发票号，发票日期，来源科室代码，名称
    sq += "'" + rcd.value("invo_no").toString() + "'," ;//-发票号

    if(rcd.value("invo_date").toString() == "--")//-发票上的发票时间
    {
        sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
    }else{
        sq += "to_date('" + rcd.value("invo_date").toString() + "','yyyy-mm-dd')," ;
    }

    sq += "'','',";

    //供货公司代码，名称，生产商代码
    sq += "'" + para["company_code"] + "'," ;
    sq += "'" + para["company_name"] + "'," ;
    sq += "'" + rcd.value("fac_code").toString() + "'," ;

    //生产日期，有效期，生产标志
    if(rcd.value("produce_date").toString() == "--")//-生产日期
    {
        sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
    }else{
        sq += "to_date('" + rcd.value("produce_date").toString() + "','yyyy-mm-dd')," ;
    }

    if(rcd.value("valid_date").toString() == "--")//-有效期
    {
        sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
    }else{
        sq += "to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd')," ;
    }

    sq += "'0',";

    //出库单号，财务标志，返回数量
    sq += "'" + rcd.value("out_bill_code").toString() + "', '0', 0," ;

    //操作员，操作日期，加库存标志 1，发票入标志0
    sq += "'" + pub::usr_code + "', SYSDATE, '1','0',";
    sq += "'" + rcd.value("memo").toString() + "'";
    sq += ")";

    qDebug()<<"插入入库记录 mat_com_input : "<<sq;

    pub::db_o.exec(sq);

    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "插入 mat_com_input 错误！\n" + pub::db_o.lastError().text() );
        return false;
    }

    if(!rcd.value("input_check_no").toString().isEmpty())
    {
        sq = " update mat_com_input_check"
             " set in_state = '1',"
             " exam_num = apply_num,"
             " exam_date = sysdate,"
             " exam_opercode = '%1',"
             " in_bill_code = '%2',"
             " serial_code = '%3',"
             " in_list_code = '%4'"
             " where input_check_no = %5";
        sq = sq.arg(pub::usr_code)
                .arg(para["bill_code"])
                .arg(para["list_code"])
                .arg(para["serial_code"])
                .arg(rcd.value("input_check_no").toString());
        qDebug()<<"变更 mat_com_input_check : "<<sq<<"\n";
        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 mat_com_input_check 失败！\n" + pub::db_o.lastError().text() );
            return false;
        }
    }

    return true;
}

void Form_yk_wzrk::on_pbRemove_clicked()
{
    if(ui->tvDest_r->currentIndex().isValid())
    {
        QString item_code = ui->tvDest_r->currentIndex().siblingAtColumn(6).data(0).toString();
        qrm->exec("delete from tmp_mat_input where item_code = '" + item_code + "'");
        showList();
    }
    else
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
}

void Form_yk_wzrk::on_pbSearch_3_clicked()
{

    search_item(ui->leKey_3->text().trimmed(),    //检索关键字
                md,                           // sqlmodel
                ui->tv_config,                 //显示列表
                "item_config");  //模式

}

void Form_yk_wzrk::on_leKey_3_returnPressed()
{
    if(ui->leKey_3->text().trimmed().isEmpty())
    {
        return;
    }
    on_pbSearch_3_clicked();
}

void Form_yk_wzrk::search_item(QString key, QSqlQueryModel *md, QTableView *tv, QString mode)
{

    qDebug()<<"录入项目检索。。。\n";

    int pos;
    QString target_dept_code, dept_code; //操作目标代码， 当前工作库房代码

    //非项目维护模式，检查当前工作库房
    if(mode != "item_config" && ui->cbbStoreDept->currentText().isEmpty())
    {
        QMessageBox::warning(this, "注意", "未指定当前工作库房！" );
        return;
    }
    else
    {
        pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
        dept_code = pub::getStr(store_depts, "^", pos);
    }

    //出入库目标单位
    if(ui->tabWidget->currentIndex() == 0)
    {
        //入
        if(ui->cbbCompany->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未指定目标单位！" );
            return;
        }
        pos = pub::searchStr(company_codes, "^", ui->cbbCompany->currentText()) + 1;
        target_dept_code = pub::getStr(company_codes, "^", pos);

        if(ui->ckb_checked_only->isChecked() &&
                    (mode == "一般入库" || mode == "核准入库"))
        {
            //只提取已经验收过的入库记录
            search_checked(target_dept_code, dept_code);
            return;
        }

    }
    else if(ui->tabWidget->currentIndex() == 1)
    {
        //出
        if( mode == "特殊出库" )
        {
            target_dept_code = dept_code;
        }
        else
        {
            if(ui->cbbReceiveDept->currentText().isEmpty())
            {
                QMessageBox::warning(this, "注意", "未指定目标单位！" );
                return;
            }
            pos = pub::searchStr(drug_consume_depts, "^", ui->cbbReceiveDept->currentText()) + 1;
            target_dept_code = pub::getStr(drug_consume_depts, "^", pos);
        }
    }
    else if(ui->tabWidget->currentIndex() == 3)
    {
        //item configuration

    }
    else
    {
        QMessageBox::warning(this, "注意", "工作模式无效！" );
        return;
    }

    if(mode == "一般入库" || mode == "特殊入库")
    {
        sq = " select mat.item_name 物资项目名称,mat.specs 规格, "//0,1
             " f_c.company_name 厂家,mat.APPROVE_INFO, "//2 - 3
                " mat.PACK_QTY,mat.PACK_UNIT, "//4,5
                " mat.sale_price,mat.in_price, mat.item_code ,"//6 - 8
                " mat.factory_code, mat.min_unit, mat.kind_code,'','' "//9 - 13
                " from mat_com_baseinfo mat "
                " LEFT JOIN mat_com_company f_c ON f_c.company_code =mat.factory_CODE "
                " where "
                " mat.valid_flag = '1' "
                " and (mat.spell_code like '%%1%' or mat.item_name like '%%2%' )"
                " order by mat.item_name";
        sq = sq.arg(key.toUpper())
                .arg(key);


    }
    else if(mode == "发票入库")
    {
        sq = " select mat.item_name 物资项目名称,mat.specs 规格,  "//0,1
             " f_c.company_name 厂家, '', mat.PACK_QTY, mat.PACK_UNIT, "//2 - 5
             " 0, mat.in_price, mat.item_code, "//6 - 8
             " '', mat.min_unit, mat.kind_code, mat.stock_code, mat.in_num "//9 - 13
             " from mat_com_input mat "
             " left JOIN mat_com_company f_c ON f_c.company_code =mat.factory_code "
             " where "
             " mat.trans_type = '1' "
             " and mat.storage_code = '%1'"
             " and mat.company_code = '%2'"
             " and mat.invoice_no is null"
             " order by mat.item_NAME";

                sq = sq.arg(dept_code)
                        .arg(target_dept_code);

    }
    else if(mode == "一般出库" || mode == "特殊出库")
    {

        sq = " select mat.item_name 物资项目名称, mat.SPECS 规格, "//0 - 1
             " f_c.company_name 厂家, base.APPROVE_INFO, "//2 - 3
                " mat.PACK_QTY, mat.PACK_UNIT,"//4 - 5
                " mat.sale_price, mat.in_price, mat.item_code, "//6 - 8
                " mat.factory_code, mat.min_unit, mat.kind_code,"//9 - 11
                " mat.stock_code, mat.store_num,";//12 - 13
        sq += " mat.batch_no 批号, mat.produce_date, mat.valid_date,"//14 - 16
              " mat.in_price, mat.stock_code, "//17 - 18
              " mat.store_num, mat.stock_no 批次"; //19 - 20
        sq += " from mat_com_stockdetail mat ";
        sq += " left join mat_com_baseinfo base on base.item_code = mat.item_code ";
        sq += " LEFT JOIN mat_com_company f_c ON f_c.company_code = mat.factory_code ";
        sq += " where mat.store_num > 0 ";
        sq += " and mat.storage_code = '" + dept_code + "' ";
        //sq += " and mat.company_code = '" + target_dept_code + "' ";
        sq += " and (base.SPELL_CODE like '%"
                + key.toUpper() + "%' or base.item_NAME like '%" + key + "%' )";
        sq += " order by base.item_name";


    }
    else if(mode.indexOf("退库") > 0)
    {
        QString dest_code, sto_code;
        if(mode == "出库退库")
        {
            sto_code = target_dept_code;
            dest_code = dept_code;
        }
        else if(mode == "入库退库")
        {
            sto_code = dept_code;
            dest_code = target_dept_code;
        }
        else
        {
            QMessageBox::warning(this, "注意", "退库方式无效！" );
            return;
        }

        sq = " select mat.item_name 物资项目名称, mat.SPECS 规格, "//0 - 1
             " f_c.company_name 厂家, base.APPROVE_INFO, "//2 - 3
                " mat.PACK_QTY, mat.PACK_UNIT,"//4 - 5
                " mat.sale_price, mat.in_price, mat.item_code, "//6 - 8
                " mat.factory_code, mat.min_unit, mat.kind_code,"//9 - 11
                " mat.stock_code, mat.store_num,";//12 - 13
        sq += " mat.batch_no 批号, mat.produce_date, mat.valid_date,"//14 - 16
              " mat.in_price, mat.in_no, mat.store_num, mat.stock_no 批次"; //17 - 20
        sq += " from mat_com_stockdetail mat ";
        sq += " left join mat_com_baseinfo base on base.item_code = mat.item_code ";
        sq += " LEFT JOIN mat_com_company f_c ON f_c.company_code = mat.factory_code ";
        sq += " where mat.store_num > 0 ";
        sq += " and mat.storage_code = '" + sto_code + "' ";
        sq += " and mat.company_code = '" + dest_code + "' ";
        sq += " and (base.SPELL_CODE like '%"
                + key.toUpper() + "%' or base.item_NAME like '%" + key + "%' )";
        sq += " order by base.item_name";

    }
    else if(mode == "item_config")
    {

        sq = " select distinct mat.item_name 名称, mat.specs 规格, "
             " f_c.company_name 厂家, mat.item_code "
             " from mat_com_baseinfo mat ";
        sq += " left join mat_com_company f_c on f_c.company_code =mat.factory_code ";
        sq += " left join mat_com_stockdetail sto on sto.item_code =mat.item_code ";
        sq += " where (mat.spell_code like '%"
                + key.toUpper() + "%' or mat.item_name like '%" + key + "%') ";

        QString v = "'v'";
        if(ui->ckb_in_use_2->isChecked())
        {
            v = v + ",'1'";
        }

        if(ui->ckb_un_use_2->isChecked())
        {
            v = v + ",'0'";
        }

        sq += " and mat.valid_flag in (" + v + ") ";

        if(ui->ckb_no_zero->isChecked())
        {
            sq += " and sto.store_num > 0 ";
        }
        sq += " order by mat.item_name";

    }
    else
    {
        QMessageBox::warning(this, "注意", "出入库方式无效！" );
        return;

    }

    qDebug()<<"目录检索："<<sq;
    md->setQuery(sq, pub::db_o);

    tv->setModel(md);
    int width = tv->width();
    if(mode == "一般出库"
            || mode == "报损"
            || mode == "特殊出库"
            || mode.indexOf("退库") > 0
            )
    {
        pub::setColumnWidth(tv, "0.25^0.2^0.20^0^0^0^0^0^0^0^0^0^0^0^0.2^0^0^0^0", width, 20);
    }
    else
    {
        pub::setColumnWidth(tv, "0.3^0.2^0.35^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0", width, 25);
    }

    //检索成功之后，禁止修改库存单位
    if(ui->tabWidget->currentIndex() == 0)
    {
        change_lock_status("in", false);
    }
    else if(ui->tabWidget->currentIndex() == 1)
    {
        change_lock_status("out", false);
    }

}

void Form_yk_wzrk::on_lePh_returnPressed()
{
    if(ui->lePh->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->leScrq->setFocus();
        ui->leScrq->selectAll();
    }
}

void Form_yk_wzrk::on_leScrq_returnPressed()
{
    ui->leXq->setFocus();
    ui->leXq->selectAll();
}

void Form_yk_wzrk::on_leXq_returnPressed()
{
    ui->leRksl->setFocus();
}

void Form_yk_wzrk::on_pbSearch_2_clicked()
{
    search_item(ui->leKey_2->text().trimmed(),
                mdcs,
                ui->tvSource_c,
                ui->cbbMode_c->currentText());
}

void Form_yk_wzrk::on_leKey_2_returnPressed()
{
    if(ui->leKey_2->text().trimmed().isEmpty())
    {
        return;
    }
    on_pbSearch_2_clicked();
}


void Form_yk_wzrk::on_pbAdd_2_clicked()
{

    if(!checkStatus("output_add_item"))
    {
        return;
    }

    //出库数据插入临时表
    sq = "replace into tmp_mat_input ("
         "item_code, item_name, company_code, "
         "company_name, specs, approve_info, ";  //物资项目编码,品名,生产商,规格,批准文号
    sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,物资项目中药西药类别
    sq += "drug_quality, sale_price, in_price,";   //物资项目类别，零售价格,采购价格
    sq += "med_list_codg,"; //存储 in_no ,
    sq += "batch_no, produce_date, valid_date, num,";   //批号,生产日期,效期,数量
    sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost ,";   //发票号, 发票日期, 备注， 购入金额，零售金额
    sq += "out_bill_code, out_list_code, out_serial_code, "
          " group_code, num_before, stock_no";//
    sq += ") values(";
    sq += "'" + item_detail["item_code"] + "',";//物资项目编码
    sq += "'" + item_detail["item_name"] + "',";//品名
    sq += "'" + item_detail["fac_code"] + "',";//生产商
    sq += "'" + item_detail["fac_name"] + "',";//生产商
    sq += "'" + item_detail["specs"] + "',";//规格
    sq += "'" + item_detail["approve_info"] + "',";//批准文号
    sq += "'" + item_detail["pack_qty"] + "',";//包装数量
    sq += "'" + item_detail["pack_unit"] + "',";//包装单位
    sq += "'" + item_detail["kind_code"] + "',";//物资项目类别，kind_code/drug_type
    sq += "'" + item_detail["drug_quality"] + "',";//物资项目类别，普药，特药
    sq += "'" + item_detail["sale_price"] + "',";//零售价格
    sq += "'" + ui->leGrjg_2->text().trimmed() + "',";//采购价格
    sq += "'" + item_detail["med_list_codg"] + "',";//医保码
    sq += "'" + ui->lePh_2->text().trimmed() + "',";//批号
    sq += "'" + ui->leScrq_2->text().trimmed() + "',";//生产日期
    sq += "'" + ui->leXq_2->text().trimmed() + "',";//效期
    sq += "'" + QString::number(ui->leRksl_2->text().toInt()
                                * item_detail["pack_qty"].toInt()) + "',";//数量
    sq += "'" + ui->leFph_2->text().trimmed() + "',";//发票号
    sq += "'" + ui->leFprq_2->text().trimmed() + "',";//发票日期
    sq += "'" + ui->leBz_2->text().trimmed() + "',";//备注
    sq += "'" + item_detail["min_unit"] + "',";//备注
    sq += ui->leGrje_2->text()+ ",";//购入金额
    sq += item_detail["sale_price"] + " * ("
            + ui->leRksl_2->text().trimmed() +")," ;//零售金额
    sq += "'" + item_detail["out_bill_code"] + "',";//
    sq += "'" + item_detail["out_list_code"] + "',";//
    sq += "'" + item_detail["out_serial_code"] + "',";//
    sq += "'" + item_detail["stock_code"] + "',";//
    sq += "'" + item_detail["store_sum"] + "',";//
    sq += "'" + item_detail["stock_no"] + "'";//

    sq += ")";


    qDebug()<<"insert data to temporary table : "<< sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
        return ;
    }

    showList();
}

void Form_yk_wzrk::on_tvSource_c_clicked(const QModelIndex &index)
{
    item_selected(index);
}

void Form_yk_wzrk::on_tvSource_c_doubleClicked(const QModelIndex &index)
{
    on_tvSource_c_clicked(index);
}

void Form_yk_wzrk::on_leRksl_2_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_wzrk::on_pbRemove_2_clicked()
{
    if(ui->tvDest_c->currentIndex().isValid())
    {
        QString item_code = ui->tvDest_c->currentIndex().siblingAtColumn(6).data(0).toString();
        qrm->exec("delete from tmp_mat_input where item_code = '" + item_code + "'");
        showList();
    }
    else
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
}

void Form_yk_wzrk::on_pbSave_2_clicked()
{

    qDebug()<<"出库保存例程。。。\n";

    if(!checkStatus("output_save_invoice"))
    {
        return;
    }
    int pos;

    //出库类型
    pos = pub::searchStr(mode_code_c, "^", ui->cbbMode_c->currentText());
    QString out_type = pub::getStr(mode_code_c, "^", pos + 1);
    QString class2_code = pub::getStr(mode_code_c, "^", pos + 2);

    //检索出库科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    //检索科室代码
    pos = pub::searchStr(drug_consume_depts, "^", ui->cbbReceiveDept->currentText()) + 1;
    QString receive_dept_code = pub::getStr(drug_consume_depts, "^", pos);

    //生成 out_list_code
    QString out_list_code ;
    sq = "select max(out_list_code) + 1 from mat_com_output ";
    qDebug()<<"获取当前最大单据号:"<<sq;
    qro->exec(sq);
    qro->next();
    QString sn = qro->value(0).toString();

    out_list_code = QString("0000000000").replace(10 - sn.length(), sn.length(), sn);

    //按临时表记录数生成 出库流水号，
    QStringList out_nos;//, stock_codes, stock_no;

//    if(ui->cbbMode_c->currentText() == "一般出库"
//            || ui->cbbMode_r->currentText() == "出库退库"
//            )
    {
        //
        sq = "select count(*) from tmp_mat_input ";
        qrm->exec(sq);
        qrm->next();
        int count = qrm->value(0).toInt();

        if( count < 1)
        {
            QMessageBox::warning(this, "注意", "临时表数据为空！");
            return ;
        }

        while(count > 0)
        {

            sq = "SELECT SEQ_MAT_OUTNO.NEXTVAL FROM DUAL";
            qDebug()<<"生成 _code ："<<sq;

            if(qro->exec(sq))
            {
                qro->next();
                //stock_codes << qro->value(0).toString();
                out_nos << qro->value(0).toString();
                //stock_no << qro->value(2).toString();
            }
            else
            {
                QMessageBox::warning(this, "注意", "未能获取出库需要的序列号 ！");
                return ;
            }

            count --;
        }
    }

    QSqlRecord rcd;
    QMap<QString, QString> para;
    para["dept_code"] = dept_code;  //库存单位
    para["io_type"] = out_type;   //出库类型
    para["class2_code"] = class2_code;   //
    para["receive_dept_code"] = receive_dept_code; //物资项目接收诊室
    para["in_out"] = "out"; //入，出

    para["state"] = "2";//0 申请， 1审批， 2核准

    if(ui->cbbMode_c->currentText() == "出库退库" )
    {
//        para["state"] = "2";//0 申请， 1审批， 2核准
        //退库进行负数计算
        para["mode"] = "-";
    }
    else
    {

//        if(ui->cbbMode_c->currentText() == "报损"
//                || ui->cbbMode_c->currentText() == "特殊出库"
//                )
//        {
//            para["state"] = "2";//0 申请， 1审批， 2核准
//        }else{
//            para["state"] = "1";//0 申请， 1审批， 2核准
//        }
        para["mode"] = "";
    }


    pub::db_o.transaction();

    QString tmpSql ;
    QSqlQuery tmpQr ;

    sq = "select * from tmp_mat_input ";
    qrm->exec(sq);

    int serial_int = 0; //页内序号,
    int count = 0;

    while(qrm->next())
    {

        serial_int ++ ;//页面内部行号

        if(serial_int > MAX_LINES)
        {
            //每页限制行数
            serial_int = 1;

            QString sn = QString::number(out_list_code.toInt() + 1);
            out_list_code = QString("0000000000").replace(10 - sn.length(), sn.length(), sn);

        }

        para["list_code"] = out_list_code;   //单据号
        para["serial_code"] = QString::number(serial_int);   //

        //para["stock_code"] = qrm->value("group_code").toString();   //批次号
        para["out_no"] = out_nos[count];   //流水号
        //para["stock_no"] = stock_no[count];   //库存流水号

        //临时表当前行数据
        rcd = qrm->record();

//        tmpSql = "select max(out_list_code) from mat_com_input ";
//        qDebug()<<"获取当前最大出库单据号:"<<tmpSql;

        //生成 out_bill_code
//        tmpSql = "SELECT SEQ_mat_OUTBILL_ID.NEXTVAL FROM DUAL";
//        tmpQr = pub::db_o.exec(tmpSql);
//        tmpQr.next();
//        para["bill_code"] = tmpQr.value(0).toString();

        //保存 mat_com_output
        if(!ins_output(rcd, para))
        {
            pub::db_o.rollback();
            return;
        }

        //保存 mat_com_stockdetail
        if(!ins_storage(rcd, para))
        {
            pub::db_o.rollback();
            return;
        }

        //无人工核准入库中过程，直接自动进行核准操作
        if(ui->cbbMode_c->currentText() == "出库退库")
        {
            if(!check_input(rcd, para, "back"))
            {
                pub::db_o.rollback();
                return ;
            }
        }
        else if(ui->cbbMode_c->currentText() == "一般出库")
        {
            if(!check_input(rcd, para, "out"))
            {
                pub::db_o.rollback();
                return ;
            }
        }
        else
        {
            //特殊出库不需要核准
        }

        count++;

    }

    pub::db_o.commit();
    qrm->exec("delete from tmp_mat_input");
    showList();
    change_lock_status("out", true);
}

bool Form_yk_wzrk::ins_output(QSqlRecord rcd, QMap<QString, QString> para)
{

    qDebug()<<"出库记录表管理。。。\n";

    sq = " INSERT INTO MAT_COM_outPUT ( ";
    sq += " out_no, out_list_code, out_serial_no,"; //入库流水号，入库单号，单据内流水号
    sq += " storage_code, stock_code, out_class3,"; //库房代码，库存流水号，入库类别
    sq += " trans_type, out_state,"; //交易类别，入库状态
    sq += " item_code, item_name, kind_code,";//项目代码，项目名称，库存类别
    sq += " specs, batch_no,out_num,min_unit,";//规格，批号，数量，最小单位
    sq += " priv_store_num, pack_unit, pack_qty,";//出前数量，包装单位，每包数量
    sq += " out_price,out_cost,add_rate,sale_price,sale_cost,";//入价，入金额，价率，零售价，零售金额
    sq += " out_date, apply_oper,apply_date,";//入日期，申请操作员，申请日期
    sq += " exam_oper, exam_date, approve_oper, approve_date, ";//审核员，审核日期，核准员，核准日期
    sq += "  target_dept, "; //出库目标科室，
    sq += " produce_date, valid_date,";//生产日期，有效期
    sq += " finance_flag, return_num, ";//财务标志，退库数量
    sq += " oper_code, oper_date,memo";//操作员，操作日期，加库存标志 1，发票入标志0  , is_addstore,is_invoicein

    sq += " ) values (";

    //入库流水号 入库单据号 单据内流水号
    sq += "'" + para["out_no"] + "' ,";
    sq += "'" + para["list_code"] + "' ,";
    sq += "'" + para["serial_code"] + "' ,";

    //库房代码，库存流水号，入库类别
    sq += "'" + para["dept_code"] + "' ,";
    sq += "'" + rcd.value("group_code").toString() + "' ,";
    sq += "'" + para["io_type"] + "' ,";

    //交易类别
    if(para["mode"] == "")
    {
        sq += "'1' ,";
    }
    else
    {
        sq += "'2' ,";
    }

    //入库状态, 直接设置核准状态
    sq += "'2' ,";

    //项目代码，项目名称，库存类别
    sq += "'" + rcd.value("item_code").toString() + "'," ; //-物资项目编码
    sq += "'" + rcd.value("item_name").toString() + "'," ; //-物资项目商品名
    sq += "'" + rcd.value("drug_type").toString() + "'," ; //-物资项目类别 drug_type/kind_code

    //规格，批号，入库数量，最小单位
    sq += "'" + rcd.value("specs").toString() + "'," ; //-规格
    sq += "'" + rcd.value("batch_no").toString() + "'," ; //批号
    sq += para["mode"] + rcd.value("num").toString() + ", " ; //-购入数量
    sq += "'" + rcd.value("min_unit").toString() + "'," ; //最小单位

    //出前数量，包装单位，每包数量
    sq += "'" + rcd.value("num_before").toString() + "'," ; //出前数量
    sq += "'" + rcd.value("pack_unit").toString() + "'," ; //包装单位
    sq += "'" + rcd.value("pack_qty").toString() + "'," ; //包装数

    //入价，入金额，价率，零售价，零售金额
    sq += rcd.value("in_price").toString() + ", " ; //-购入价
    sq += para["mode"] + rcd.value("purchase_cost").toString() + "," ; //-购入金额
    sq += "0,";
    sq += rcd.value("sale_price").toString() + "," ; //-零售价
    sq += para["mode"] + rcd.value("retail_cost").toString() + "," ; //-零售金额

    //入日期，申请操作员，申请日期
    sq += " sysdate, '', sysdate,";

    //审核员，审核日期，核准员，核准日期
    sq += "'', sysdate,'',sysdate,";

    //目标科室代码，
    sq += "'" + para["receive_dept_code"] + "',";

    //生产日期，有效期，生产标志
    if(rcd.value("produce_date").toString() == "--")//-生产日期
    {
        sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
    }else{
        sq += "to_date('" + rcd.value("produce_date").toString() + "','yyyy-mm-dd')," ;
    }

    if(rcd.value("valid_date").toString() == "--")//-有效期
    {
        sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
    }else{
        sq += "to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd')," ;
    }


    //财务标志，退库数量
    sq += "'0', 0," ;

    //操作员，操作日期，加库存标志 1，发票入标志0
    sq += "'" + pub::usr_code + "', SYSDATE,"; //, '1','0'
    sq += "'" + rcd.value("memo").toString() + "'";
    sq += ")";

    qDebug()<<"插入出库记录 mat_com_output : "<<sq;

    pub::db_o.exec(sq);

    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "插入 mat_com_output 错误！\n" + pub::db_o.lastError().text() );
        return false;
    }

    return true;
}


void Form_yk_wzrk::on_cbbMode_r_currentTextChanged(const QString &arg1)
{
    if(!initialFinished)
    {
        return;
    }
    if(arg1 == "一般入库" || arg1 == "发票入库" || arg1.indexOf("退库") > 0 )
    {
        sq = "select company_name, company_code from mat_com_company where COMPANY_TYPE = '1' and VALID_FLAG = '1' order by company_name";
        qDebug()<<"提取库存操作目标："<<sq;
        company_codes = pub::fillCombo(ui->cbbCompany, sq, -1, qrot);
    }
    else if(arg1 == "核准入库" ||  arg1 == "特殊入库")
    {
        sq  = "select dept_name,dept_code from com_department where "
              " valid_state = '1' and dept_type in ('L','P','PI') order by dept_type,dept_name";//,'N' ,护士站
        qDebug()<<"提取核准入库目标："<<sq;
        company_codes = pub::fillCombo(ui->cbbCompany, sq, -1, qrot);
    }
    else
    {
        ui->cbbCompany->clear();
    }
}

void Form_yk_wzrk::on_cbbReceiveDept_currentIndexChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    if(!initialFinished)
    {
        return;
    }

    qrm->exec("delete from tmp_mat_input");
    showList();
}

void Form_yk_wzrk::on_leRksl_2_returnPressed()
{
    if(ui->leRksl_2->text().isEmpty())
    {
        return;
    }
    ui->pbAdd_2->setFocus();
}

void Form_yk_wzrk::on_leRksl_returnPressed()
{

    if(ui->leRksl->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->leFph->setFocus();
    }

}

QRectF Form_yk_wzrk::getRealPosition(int row, int col)
{

    float x1,x2,y1,y2;
    if(col > 0)
    {
        //单个单元格
        x1 = (grid_col[ col - 1 ].toDouble() + margin + xPos) * ptScale;
        x2 = (grid_col[ col ].toDouble() - margin + xPos) * ptScale;
    }
    else
    {
        //合并单元格
        int col1,col2;
        col1 = (0 - col) / 100;
        col2 = (0 - col) % 100;
        x1 = (grid_col[ col1 - 1 ].toDouble() + margin + xPos) * ptScale;
        x2 = (grid_col[ col2 ].toDouble() - margin + xPos) * ptScale;
    }
    if(row > 0 )
    {
        y1 = (grid_row[ row - 1 ].toDouble() + yPos) * ptScale;
        y2 = (grid_row[ row ].toDouble() + yPos) * ptScale;
    }
    else
    {
        int row1,row2;
        row1 = (0 - row) / 100;
        row2 = (0 - row) % 100;
        y1 = (grid_row[ row1 - 1 ].toDouble() + yPos) * ptScale;
        y2 = (grid_row[ row2 ].toDouble() + yPos) * ptScale;
    }
    QPointF p1 = QPointF(x1, y1);
    QPointF p2 = QPointF(x2, y2);
//qDebug()<<"get real position : "<<QString::number(row)<<","<<QString::number(col)<<","<<p1<<","<<p2;
    return QRectF(p1 , p2);

}

void Form_yk_wzrk::printCellItem(QString item_name, QString item_value, int pos)
{
    sq = "select p_type,p_item,p_top,p_left,p_width,p_height,p_font_name,p_font_size,"
         " p_position,p_mode,p_print_item,p_item_type from com_printer_setting "
         " where p_type = '物资入出' and p_item_type = 'item'"
         " and p_item = '" + item_name + "'";
    qrmp->exec(sq);

    if(!qrmp->next())
    {
        QMessageBox::information(this, "注意", "项目名称 " + item_name + " 不存在 ！");
        return;
    }

    QFont ft;
    ft.setPixelSize(int(ptScale * qrmp->value("p_font_size").toDouble()));
    ft.setFamily(qrmp->value("p_font_name").toString());
    pnt->setFont(ft);

    int flag;
    if(qrmp->value("p_position").toInt() == 0)
    {
        //左
        flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft ;
    }
    else if(qrmp->value("p_position").toInt() == 1)
    {
        //中
        flag = Qt::AlignCenter ;//Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignHCenter
    }
    else
    {
        //右
        flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignRight ;
    }

    QRectF f; //打印范围区域

    if( qrmp->value("p_width").toInt() == 0
            && qrmp->value("p_height").toInt() == 0)
    {
        //以表格为参照，需要进行换算
        f = getRealPosition(qrmp->value("p_top").toInt() + pos , qrmp->value("p_left").toInt());
    }
    else
    {
        f = QRectF((qrmp->value("p_left").toDouble() + xPos) * ptScale,
                   (qrmp->value("p_top").toDouble() + yPos) * ptScale,
                   (qrmp->value("p_width").toDouble())  * ptScale,
                   (qrmp->value("p_height").toDouble()) * ptScale);
    }

    pnt->drawText(f, flag, item_value, NULL);

}

void Form_yk_wzrk::printPageBase()
{

    //表格线
    double x1, y1, x2, y2, width ;
    QPen p ;
    p.setStyle(Qt::SolidLine);

    sq = "select p_type,p_item,p_top,p_left,p_width,p_height,p_font_name,p_font_size,"
         "p_position,p_mode,p_print_item,p_item_type from com_printer_setting "
         "where p_type = '物资入出' and p_item_type = 'base'";
    qrmp->exec(sq);
    while(qrmp->next())
    {
        if(qrmp->value("p_item").toString() == "grid_col")
        {
            grid_col = qrmp->value("p_print_item").toString().split("^");
        }
        else if(qrmp->value("p_item").toString() == "grid_row")
        {
            grid_row = qrmp->value("p_print_item").toString().split("^");
        }
    }

    qrmp->first();
    while(true)
    {
        if( qrmp->value("p_item").toString() == "line_landscape")
        {
            width = qrmp->value("p_font_size").toDouble();
            x1 = (qrmp->value("p_top").toDouble() + xPos) * ptScale;
            y1 = (qrmp->value("p_left").toDouble() + yPos) * ptScale;
            x2 = (qrmp->value("p_width").toDouble() + xPos) * ptScale;
            y2 = (qrmp->value("p_height").toDouble() + yPos) * ptScale;

            p.setWidth( ptScale * width);
            pnt->setPen(p);
            pnt->drawLine(x1, y1, x2, y2);

            QStringList stepList = qrmp->value("p_print_item").toString().split("^");

            for(int i = 0; i < stepList.size(); i++)
            {
                y1 = (stepList[i].toDouble() + yPos) * ptScale ;
                y2 = (stepList[i].toDouble() + yPos) * ptScale ;
                pnt->drawLine(x1, y1, x2, y2);
            }

        }
        else if( qrmp->value("p_item").toString() == "line_portrait")
        {
            width = qrmp->value("p_font_size").toDouble();
            x1 = (qrmp->value("p_top").toDouble() + xPos) * ptScale;
            y1 = (qrmp->value("p_left").toDouble() + yPos) * ptScale;
            x2 = (qrmp->value("p_width").toDouble() + xPos) * ptScale;
            y2 = (qrmp->value("p_height").toDouble() + yPos) * ptScale;

            p.setWidth( ptScale * width);
            pnt->setPen(p);
            pnt->drawLine(x1, y1, x2, y2);
            //QString step = qrmp->value("p_item").toString();
            QStringList stepList = qrmp->value("p_print_item").toString().split("^");

            for(int i = 0; i < stepList.size(); i++)
            {
                x1 = (stepList[i].toDouble() + xPos) * ptScale ;
                x2 = (stepList[i].toDouble() + xPos) * ptScale ;
                pnt->drawLine(x1, y1, x2, y2);
            }

        }
        else if( qrmp->value("p_item").toString() == "solid")
        {
            QFont ft;
            ft.setPixelSize(int(ptScale * qrmp->value("p_font_size").toDouble()));
            ft.setFamily(qrmp->value("p_font_name").toString());
            pnt->setFont(ft);

            int flag;
            if(qrmp->value("p_position").toInt() == 0){ //左
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft ;
            }else if(qrmp->value("p_position").toInt() == 1){//中
                flag = Qt::AlignCenter ;//Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignHCenter
            }else{          //右
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignRight ;
            }

            QString txt = qrmp->value("p_print_item").toString();

            QRectF f; //打印范围区域

            if( qrmp->value("p_width").toInt() == 0
                    && qrmp->value("p_height").toInt() == 0)
            {
                //以表格为参照，需要进行换算
                f = getRealPosition(qrmp->value("p_top").toInt(), qrmp->value("p_left").toInt());
            }
            else
            {
                f = QRectF((qrmp->value("p_left").toDouble() + xPos) * ptScale,
                           (qrmp->value("p_top").toDouble() + yPos) * ptScale,
                           (qrmp->value("p_width").toDouble())  * ptScale,
                           (qrmp->value("p_height").toDouble()) * ptScale);
            }

            pnt->drawText(f, flag, txt, NULL);
        }
        if(!qrmp->next())
        {
            break;
        }
    }
}

void Form_yk_wzrk::on_pbPrintOut_clicked()
{
    if(ui->lwToPrint->count() == 0)
    {
        QMessageBox::warning(this, "注意", "未选定打印的出入库单！");
        return ;
    }

    QString io, io_list_code;
    QMap<QString, QString> printItem;

    for(int i = 0; i < ui->lwToPrint->count() ; i++)
    {
        printItem.clear();

        io = pub::getStr(ui->lwToPrint->item(i)->text(), "^", 1);
        io_list_code = pub::getStr( ui->lwToPrint->item(i)->text(), "^", 2);

        qDebug()<<"io_list_code is : "<<io<<","<<io_list_code;

        if(io == "入库单")
        {
            sq = " select storage_code, in_list_code 单据号,"
                 " in_class3, item_code 物资项目编码, "
                 " item_name 物资项目名称, specs 规格, "
                 " in_num / pack_qty 数量, pack_unit 单位, "
                 " in_price 价格, in_cost 金额,"//, sale_price 销售价, retail_cost 销售金额
                 " memo, batch_no 批号, "//retail_cost - purchase_cost 差价,
                 " to_char(valid_date, 'yyyy-mm-dd') 效期, company_code , "
                 " to_char(in_date, 'yyyy-mm-dd') in_date, oper_code "
                 " from mat_com_input"
                 " where in_num <> 0 and in_list_code = '"
                    + io_list_code +"' order by in_serial_no";
        }
        else
        {
            sq = " select storage_code, out_list_code 单据号,"
                 " out_class3, item_code 物资项目编码, "
                 " item_name 物资项目名称, specs 规格, "
                 " out_num / pack_qty 数量, pack_unit 单位, "
                 " out_price 价格, out_cost 金额,"//out_price 购入价, approve_cost 购入金额,
                 "  memo, batch_no 批号, "//sale_cost - approve_cost 差价,
                 " to_char(valid_date, 'yyyy-mm-dd') 效期, "
                 " target_dept company_code , "
                 " to_char(out_date, 'yyyy-mm-dd') out_date, oper_code,"
                 " (priv_store_num - out_num) / pack_qty 库存"
                 " from mat_com_output"
                 " where out_num <> 0 and out_list_code = '"
                    + io_list_code +"' order by out_serial_no";
        }

qDebug()<<" prepare to print: "<<sq;
        qro->exec(sq);
        qro->next();

        printItem["库房"] = "库房：" + ui->cbbStoreDept->currentText();
        printItem["单据号"] = "单据号：" + io_list_code;

        if(io == "入库单")
        {
            sq = "select company_name from mat_com_company where company_code = '"
                    + qro->value("company_code").toString() + "' ";
            qrot->exec(sq);
            qrot->next();
            printItem["目标单位"] = "供货商：" + qrot->value(0).toString() ;
            printItem["出入日期"] = "入库日期：" + qro->value("in_date").toString() ;
            sq = "select class3_name from com_priv_class3 where class3_code = '"
                    + qro->value("in_class3").toString() + "' and class2_code = '0310'";

        }
        else
        {
            //出库单
            sq = "select dept_name from com_department where valid_state = '1' and dept_code = '"
                    + qro->value("company_code").toString() + "' ";
            qrot->exec(sq);
            qrot->next();
            printItem["目标单位"] = "出库去向：" + qrot->value(0).toString() ;
            printItem["出入日期"] = "出库日期：" + qro->value("out_date").toString() ;
            sq = "select class3_name from com_priv_class3 where class3_code = '"
                    + qro->value("out_class3").toString() + "' and class2_code = '0320'";

        }
        qrot->exec(sq);
        qrot->next();
        printItem["标题"] = ui->cbbStoreDept->currentText() + io + "(" + qrot->value(0).toString() + ")";

        printItem["请领人"] = "请领人:";

        qrm->exec("select empl_name from com_employee where empl_code = '"
                  + qro->value("oper_code").toString() + "'");
        qrm->next();

        printItem["操作员"] = "操作员:" + qrm->value(0).toString();//pub::usr_name;
        printItem["打印日期"] = "打印日期：" + QDateTime::currentDateTime().toString("yyyy-MM-dd");

        pnt->begin(prt);
        printPageBase();
        QMap<QString, QString>::iterator itor;
        for(itor = printItem.begin(); itor != printItem.end(); itor++)
        {
            printCellItem(itor.key(), itor.value(), 0 );
            qDebug()<<itor.key()<<","<< itor.value();
        }

        double all_cost = 0;
        //double all_cost_in = 0;    //单据购入金额
        //double all_cost_out = 0;    //单据销价金额
        //double all_cost_diff = 0;    //差价
        QString batch_valid = "物资项目编码,批号,效期 : \n";    //物资项目编码 ，批号，效期
        QString mark = "备注 : ";    //备注
        int lines = 0;  //单据内行序数
        printItem.clear();
        while(true)
        {
            //printItem["物资项目编码"] = qro->value("物资项目编码").toString();
            printItem["物资项目名称"] = qro->value("物资项目名称").toString();
            printItem["规格"] = qro->value("规格").toString();
            printItem["数量"] = qro->value("数量").toString();
            printItem["单位"] = qro->value("单位").toString();
            printItem["价格"] = QString::number(qro->value("价格").toDouble(),'f',2) ;
            printItem["金额"] = QString::number(qro->value("金额").toDouble(),'f',2) ;
            if(io == "出库单")
            {
                printItem["库存"] = qro->value("库存").toString() ;
            }

            //printItem["购入价"] = QString::number(qro->value("购入价").toDouble(),'f',2) ;
            //printItem["购入金额"] = QString::number(qro->value("购入金额").toDouble(),'f',2) ;
            //printItem["销售价"] = QString::number(qro->value("销售价").toDouble(),'f',2) ;
            //printItem["销售金额"] = QString::number(qro->value("销售金额").toDouble(),'f',2) ;
            //printItem["差价"] = QString::number(qro->value("差价").toDouble(),'f',2) ;

            for(itor = printItem.begin(); itor != printItem.end(); itor++)
            {
                printCellItem(itor.key(), itor.value(), lines );
            }

            all_cost += qro->value("金额").toDouble();

            //all_cost_in += qro->value("购入金额").toDouble();
            //all_cost_out += qro->value("销售金额").toDouble();
            //all_cost_diff += qro->value("差价").toDouble();
            batch_valid += qro->value("物资项目编码").toString() + ", " + qro->value("批号").toString() + ", " +qro->value("效期").toString() + "; ";
            if(!qro->value("memo").toString().isEmpty())
            {
                mark += qro->value("物资项目名称").toString() + ": " + qro->value("memo").toString() + ";";
            }

            if(!qro->next())
            {
                break;
            }
            lines ++;
        }

        printCellItem("合计", QString::number(all_cost, 'f', 2), 0 );
        //printCellItem("合计销", QString::number(all_cost_out, 'f', 2), 0 );
        //printCellItem("合计差", QString::number(all_cost_diff, 'f', 2), 0 );
        QString bat_mark = batch_valid;
        if(mark != "备注 : ")
        {
            bat_mark += "\n" + mark;
        }

        printCellItem("备注", bat_mark, 0 );

        pnt->end();
    }

    if(ui->ckb_clear_after_print->isChecked())
    {
        ui->lwToPrint->clear();
    }
}

void Form_yk_wzrk::on_prPrintSearch_clicked()
{
    if(ui->cbbStoreDept->currentText().isEmpty())
    {
        QMessageBox::warning(this, "注意", "未指定当前工作库房！");
        return ;
    }
    QString begin = ui->deBegin->date().toString("yyyy-MM-dd");
    QString end = ui->deEnd->date().toString("yyyy-MM-dd");
    QString dateRangeIn = " and trunc(in_date) >= to_date('" + begin + "','yyyy-mm-dd') ";
    dateRangeIn += " and trunc(in_date) <= to_date('" + end + "','yyyy-mm-dd') ";
    QString dateRangeOut = " and trunc(out_date) >= to_date('" + begin + "','yyyy-mm-dd') ";
    dateRangeOut += " and trunc(out_date) <= to_date('" + end + "','yyyy-mm-dd') ";

    //检索科室代码
    int pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    sq = "select distinct dept.dept_name 库房名称, input.in_list_code 入库单号, priv.class3_name 入库类别"
         " from mat_com_input input ";
    sq += " left join com_department dept on input.storage_code = dept.dept_code ";
    sq += " left join com_priv_class3 priv on priv.class3_code = input.in_class3 and priv.class2_code = '0510'";
    sq += " where input.storage_code = '" + dept_code + "' " +  dateRangeIn;
    sq += " order by input.in_list_code desc";
    qDebug()<<"search in list : "<<sq;
    md_p_in->setQuery(sq, pub::db_o);
    ui->tvInList->setModel(md_p_in);
    int width = ui->tvInList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvInList, "0.3^0.3^0.3", width, 10);

    sq = "select distinct dept.dept_name 库房名称, output.out_list_code 出库单号, priv.class3_name 出库类别"
         " from mat_com_output output ";
    sq += " left join com_department dept on output.storage_code = dept.dept_code ";
    sq += " left join com_priv_class3 priv on priv.class3_code = output.out_class3 and priv.class2_code = '0520'";
    sq += " where output.storage_code = '" + dept_code + "' and out_list_code is not null " +  dateRangeOut;
    sq += " order by out_list_code desc";
    qDebug()<<"search out list : "<<sq;
    md_p_out->setQuery(sq, pub::db_o);
    ui->tvOutList->setModel(md_p_out);
    width = ui->tvOutList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvOutList, "0.3^0.3^0.3", width, 10);

}

void Form_yk_wzrk::on_tvInList_clicked(const QModelIndex &index)
{
    sq = "select storage_code, in_list_code 单据号,in_class3, item_code 物资项目编码, "
         " item_name 物资项目名称, specs 规格, in_num / pack_qty 数量, pack_unit 单位, "
         " in_price 价格, in_cost 金额, memo, batch_no 批号, "
         " to_char(valid_date, 'yyyy-mm-dd') 效期 "
         " from mat_com_input"
         " where in_num <> 0 and in_list_code = '"
         + index.siblingAtColumn(1).data().toString() +"' order by in_serial_no";

    listPrintItem(sq);
}

void Form_yk_wzrk::listPrintItem(QString sq)
{
    //根据 list code 显示单据内容
    qDebug()<<"display items : "<<sq;
    md_p_brw->setQuery(sq, pub::db_o);
    ui->tvBrowse->setModel(md_p_brw);

    pub::setColumnWidth(ui->tvBrowse, "0^0.1^0^0.1^0.2^0.1^0.08^0.04^0.08^0.08^0^0.08^0.08", ui->tvBrowse->horizontalHeader()->width() , 20);
}

void Form_yk_wzrk::on_tvInList_doubleClicked(const QModelIndex &index)
{
    QString itm = "入库单^";
    itm += index.siblingAtColumn(1).data().toString();
    QList<QListWidgetItem*> found = ui->lwToPrint->findItems(itm, Qt::MatchExactly);
    if(found.size() == 0)
    {
        ui->lwToPrint->addItem(itm);
    }
}

void Form_yk_wzrk::on_tvOutList_clicked(const QModelIndex &index)
{
    sq = "select storage_code, out_list_code 单据号,out_class3, item_code 物资项目编码, "
         " item_name 物资项目名称, specs 规格, out_num / pack_qty 数量, pack_unit 单位, "
         " out_price 价格, out_cost 金额, memo, batch_no 批号, "
         " to_char(valid_date, 'yyyy-mm-dd') 效期 "
         " from mat_com_output"
         " where out_num <> 0 and out_list_code = '"
         + index.siblingAtColumn(1).data().toString() +"'order by out_serial_no";

    listPrintItem(sq);
}

void Form_yk_wzrk::on_tvOutList_doubleClicked(const QModelIndex &index)
{
    QString itm = "出库单^";
    itm += index.siblingAtColumn(1).data().toString();
    QList<QListWidgetItem*> found = ui->lwToPrint->findItems(itm, Qt::MatchExactly);
    if(found.size() == 0)
    {
        ui->lwToPrint->addItem(itm);
    }

}

void Form_yk_wzrk::on_lwToPrint_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)
    ui->lwToPrint->takeItem(ui->lwToPrint->currentRow());
}

void Form_yk_wzrk::on_leFph_returnPressed()
{
    if(ui->leFph->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->leFprq->setFocus();
        ui->leFprq->selectAll();
    }
}

void Form_yk_wzrk::on_leFprq_returnPressed()
{
    ui->pbAdd->setFocus();
}

void Form_yk_wzrk::on_leTax_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_wzrk::on_tvDest_r_clicked(const QModelIndex &index)
{
    QString item_code = index.siblingAtColumn(6).data().toString();
    sq = "select * from tmp_mat_input where item_code = '" + item_code + "'";
    qrm->exec(sq);
    qrm->next();

    ui->lePzwh->setText(qrm->value("approve_info").toString());
    ui->leScs->setText(qrm->value("company_name").toString());
    //ui->leLsjg->setText(qrm->value("sale_price").toString());;
    ui->lePackQty->setText(qrm->value("pack_qty").toString());
    ui->lePackUnit->setText(qrm->value("pack_unit").toString());
    ui->leGrjg->setText(qrm->value("in_price").toString());
    ui->lePh->setText(qrm->value("batch_no").toString());
    ui->leScrq->setText(qrm->value("produce_date").toString());
    ui->leXq->setText(qrm->value("valid_date").toString());
    ui->leRksl->setText(QString::number(qrm->value("num").toInt() / qrm->value("pack_qty").toInt()));

    ui->leFph->setText(qrm->value("invo_no").toString());
    ui->leFprq->setText(qrm->value("invo_date").toString());

}

void Form_yk_wzrk::on_tvDest_r_doubleClicked(const QModelIndex &index)
{
    on_tvDest_r_clicked(index);
}

void Form_yk_wzrk::on_pbNewDrug_clicked()
{

    sq = "SELECT SEQ_MAT_BASECODE.NEXTVAL FROM DUAL";
    qDebug()<<"生成编码："<<sq;
    qro->exec(sq);
    qro->next();
    QString base_code = "M00000000000";
    QString new_code = qro->value(0).toString();
    QString new_item_code = base_code.replace(base_code.length() - new_code.length(), new_code.length(), new_code);

    //不清除，可以利用相近品种新建
    //item_info_clear();

    ui->le_item_code->setText(new_item_code);
    is_new_drug = true;
    ui->le_sale_price->setEnabled(true);
    ui->le_in_price->setEnabled(true);
}

void Form_yk_wzrk::item_info_clear()
{
    ui->le_item_code->clear();// '物资项目编码';
    ui->le_item_name->clear();// '商品名称';
    ui->le_spell_code->clear();// '商品名拼音码';
    ui->le_specs->clear();// '规格';
    ui->le_sale_price->clear();// '参考零售价';
    ui->le_in_price->clear();// '最新购入价';
    ui->le_pack_qty->clear();// '包装数';

    ui->le_approve_info->clear();// '批文信息';
    ui->cbb_pack_unit->setCurrentIndex(-1);// '包装单位';

    ui->cbb_min_unit->setCurrentIndex(-1);//  '最小单位';
    ui->cbb_producer_code->setCurrentIndex(-1);//  '生产厂家';


    //sq = "select company_name, company_code from mat_com_company where COMPANY_TYPE = '0' and VALID_FLAG = '1' order by company_name";
    //qDebug()<<"提取生产厂家："<<sq;
    //producer_code = pub::fillCombo(ui->cbb_producer_code, sq, -1, qrot);

}

void Form_yk_wzrk::on_tv_config_clicked(const QModelIndex &index)
{
    item_selected(index);
    is_new_drug = false;
    ui->le_sale_price->setEnabled(false);
    ui->le_in_price->setEnabled(false);
}

void Form_yk_wzrk::on_tv_config_doubleClicked(const QModelIndex &index)
{
    on_tv_config_clicked(index);
}

bool Form_yk_wzrk::item_check()
{
    //有效性校验
    int test_num;
    double test_double;

    if(ui->le_item_code->text().isEmpty())  // '物资项目编码';
    {
        QMessageBox::information(this, "注意", "请先选定或新建一个物资项目项目！");
        return false;
    }

    if(ui->le_item_name->text().isEmpty())// '商品名称';
    {
        QMessageBox::information(this, "注意", "物资项目名称不可以空白！");
        ui->le_item_name->setFocus();
        return false;
    }

    if(ui->le_spell_code->text().isEmpty())// '商品名拼音码';
    {
        QMessageBox::information(this, "注意", "物资项目拼音码不可以空白！");
        ui->le_spell_code->setFocus();
        return false;
    }
    if(ui->le_specs->text().isEmpty())// '规格';
    {
        QMessageBox::information(this, "注意", "物资项目规格不可以空白！");
        ui->le_specs->setFocus();
        return false;
    }



    if(ui->le_pack_qty->text().isEmpty())// '包装数';
    {
        QMessageBox::information(this, "注意", "物资项目包装数量不可以空白！");
        ui->le_pack_qty->setFocus();
        return false;
    }
    else
    {
        test_num = ui->le_pack_qty->text().toUInt();
        if(test_num < 1)
        {
            QMessageBox::information(this, "注意", "物资项目包装数量数值无效！");
            ui->le_pack_qty->setFocus();
            return false;
        }
    }

    if(ui->cbb_mat_kind->currentText().isEmpty()) //  '类别';
    {
        QMessageBox::information(this, "注意", "物资类别不可以空白！");
        ui->cbb_mat_kind->setFocus();
        return false;
    }

    if(ui->cbb_min_unit->currentText().isEmpty()) //  '最小单位';
    {
        QMessageBox::information(this, "注意", "物资项目最小使用单位不可以空白！");
        ui->cbb_min_unit->setFocus();
        return false;
    }

    if(ui->cbb_producer_code->currentText().isEmpty()) //  '生产厂家';
    {
        QMessageBox::information(this, "注意", "物资项目生产厂家不可以空白！");
        ui->cbb_producer_code->setFocus();
        return false;
    }
    else
    {
        test_num = pub::searchStr(producer_codes, "^", ui->cbb_producer_code->currentText()) ;
        if(test_num == 0)
        {
            QMessageBox::information(this, "注意", "物资项目生产厂家名称无效！");
            ui->cbb_producer_code->setFocus();
            return false;
        }
    }

    if(ui->cbbMode_r->currentText() == "发票入库")
    {
        if(ui->leFph->text().trimmed().isEmpty()){
            QMessageBox::warning(this, "注意", "发票号不可以空白！");
            return false;
        }

        QDate dt_v = QDate::fromString(ui->leFprq->text(), "yyyy-MM-dd");
        if(!dt_v.isValid()){
            QMessageBox::warning(this, "注意", "发票日期无效！");
            return false;
        }

    }

    if(ui->le_sale_price->text().isEmpty())// '参考零售价';
    {
        QMessageBox::information(this, "注意", "物资项目参考零售价不可以空白！");
        ui->le_sale_price->setFocus();
        return false;
    }
    else
    {
        test_double = ui->le_sale_price->text().toDouble();
        if(test_double <= 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "物资项目参考零售价数量数值无效！");
            ui->le_sale_price->setFocus();
            return false;
        }
    }

    if(ui->le_in_price->text().isEmpty())// '最新购入价';
    {
        QMessageBox::information(this, "注意", "物资项目最新购入价不可以空白！");
        ui->le_in_price->setFocus();
        return false;
    }
    else
    {
        test_double = ui->le_in_price->text().toDouble();
        if(test_double < 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "物资项目最新购入价数量数值无效！");
            ui->le_in_price->setFocus();
            return false;
        }
    }


//    if(ui->le_approve_info->text().isEmpty())// '批文信息';
//    {
//        QMessageBox::information(this, "注意", "物资项目批文号不可以空白！");
//        ui->le_approve_info->setFocus();
//        return false;
//    }

    if(ui->cbb_pack_unit->currentText().isEmpty()) // '包装单位';
    {
        QMessageBox::information(this, "注意", "物资项目包装单位不可以空白！");
        ui->cbb_pack_unit->setFocus();
        return false;
    }

    return true;
}

void Form_yk_wzrk::on_pbAdd_4_clicked()
{

    if(ui->rb_inuse_baseinfo->isChecked() )
    {
        //启用的项目，进行有效性校验
        if(!item_check())
        {
            return;
        }
    }
    else
    {
        //停用项目，不进行有效性校验, 只检查库存数量
        int pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
        QString dept = pub::getStr(store_depts, "^", pos);//库存单位

        sq = "select store_num from mat_com_stockdetail "
             " where "
             " store_num > 0"
             " and item_code = '%1'"
             " and storage_code = '%2'";
        sq = sq.arg(ui->le_item_code->text())
                .arg(dept);


        qDebug()<<"检查物资库存："<<sq;
        qro->exec(sq);
        if(qro->next())
        {
            QString msg = "指定品种库存大于 0 ，确认要停用？";
            QMessageBox::StandardButton bt;
            bt = QMessageBox::question(this, "注意", msg);

            if(bt != QMessageBox::Yes)
            {
                return;
            }
        }
    }

    int pos = 0;    //检索

    if(is_new_drug)
    {
        //检查是否存在同厂家同文号品种

        sq = "select item_name from mat_com_baseinfo where ";

        pos = pub::searchStr(producer_codes, "^", ui->cbb_producer_code->currentText());
        sq += " factory_code = '" + pub::getStr(producer_codes, "^", pos + 1) + "'";//  producer_code '生产厂家';
        sq += " and approve_info = '" + ui->le_approve_info->text().trimmed() + "'";//批准文号
        sq += " and specs = '" + ui->le_specs->text().trimmed() + "'";//规格

        qDebug()<<"检查物资项目重复："<<sq;
        qro->exec(sq);
        if(qro->next())
        {
            QMessageBox::information(this, "注意", "指定品种的厂家和规格已经存在！");
            return;

//            QMessageBox::StandardButton bt;
//            bt = QMessageBox::information(this, "注意", "指定品种的厂家和规格已经存在！",
//                                          QMessageBox::Yes | QMessageBox::No);
//            if(bt != QMessageBox::Yes)
//            {
//                return;
//            }
        }

        //插入新品种
        sq = "insert into mat_com_baseinfo ";
        sq += "( "
              "special_flag, highvalue_flag, pack_price, add_rate, "
              "company_code, pack_flag, "//register_date, over_date,
              "examine_flag, batch_flag, plan, prestock_flag, "
              "used_flag, validdate_flag,"//以上未用
              "item_code, item_name, spell_code,"
              "kind_code, storage_code, effect_area, "
              "effect_dept, specs, min_unit, "
              "in_price, sale_price, pack_unit, "
              "pack_qty, valid_flag, "
              "factory_code, oper_code, oper_date "
              ") values ("
              "'0', '0', 0, 2, '', '0','0','0','0','0','0','0', ";
        sq += "'" + ui->le_item_code->text() + "',";// item_code'物资项目编码';
        sq += "'" + ui->le_item_name->text().trimmed() + "',";//  item_name'商品名称';
        sq += "'" + ui->le_spell_code->text().trimmed().toUpper() + "',";//  spell_code'商品名拼音码';

        pos = pub::searchStr(mat_kind, "^", ui->cbb_mat_kind->currentText()); //
        sq += "'" + pub::getStr(mat_kind, "^", pos + 1) + "',";// kind_code '系统类别';

        pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
        sq += "'" + pub::getStr(store_depts, "^", pos) + "',";//库存单位

        if(ui->cbb_dept_code->currentText().isEmpty()
                || ui->cbb_dept_code->currentText() == "通用")
        {
            sq += "'2',"; //
            sq += "'',"; //
        }
        else
        {
            sq += "'3',"; //
            pos = pub::searchStr(drug_consume_depts, "^", ui->cbb_dept_code->currentText());
            sq += "'" + pub::getStr(drug_consume_depts, "^", pos + 1) + "',";//
        }

        sq += "'" + ui->le_specs->text().trimmed() + "',";// specs '规格';
        sq += "'" + ui->cbb_min_unit->currentText() + "',"; // min_unit'最小单位';
        sq += ui->le_in_price->text() + ",";// in_price '最新购入价';
        sq += ui->le_sale_price->text() + ",";// sale_price '参考零售价';
        sq += "'" + ui->cbb_pack_unit->currentText() + "',"; //pack_unit'包装单位';
        sq += ui->le_pack_qty->text() + ",";// pack_qty '包装数';

        if(ui->rb_inuse_baseinfo->isChecked())
        {
            sq += "'1',"; //
        }
        else
        {
            sq += "'0',"; //
        }

        pos = pub::searchStr(producer_codes, "^", ui->cbb_producer_code->currentText());
        sq += "'" + pub::getStr(producer_codes, "^", pos + 1) + "',";//  producer_code '生产厂家';

        sq += "'" + pub::usr_code + "',";// oper_code '操作员';
        sq += "sysdate";// + oper_date '操作时间';

        sq += ")";
        qDebug()<<"插入新的物资项目基础数据："<<sq;
    }
    else
    {
        //更新旧数据

        sq = " update mat_com_baseinfo set ";

        if(ui->rb_inuse_baseinfo->isChecked())
        {
            sq += " valid_flag = '1',"; //
            sq += " min_unit = '" + ui->cbb_min_unit->currentText() + "',"; // min_unit'最小单位';
            sq += " item_name = '" + ui->le_item_name->text().trimmed() + "',";//  item_name'商品名称';
            sq += " spell_code = '" + ui->le_spell_code->text().trimmed().toUpper() + "',";//  spell_code'商品名拼音码';
            sq += " specs = '" + ui->le_specs->text().trimmed() + "',";// specs '规格';
            sq += " sale_price = " + ui->le_sale_price->text() + ",";// sale_price '参考零售价';
            sq += " in_price = " + ui->le_in_price->text() + ",";// in_price '最新购入价';
            sq += " pack_unit = '" + ui->cbb_pack_unit->currentText() + "',"; //pack_unit'包装单位';
            sq += " pack_qty = " + ui->le_pack_qty->text() + ",";// pack_qty '包装数';

            if(ui->cbb_dept_code->currentText().isEmpty()
                    || ui->cbb_dept_code->currentText() == "通用")
            {
                sq += " effect_area = '2',"; //
                sq += " effect_dept = '',"; //
            }
            else
            {
                sq += " effect_area = '3',"; //
                pos = pub::searchStr(drug_consume_depts, "^", ui->cbb_dept_code->currentText());
                sq += " effect_dept = '" + pub::getStr(drug_consume_depts, "^", pos + 1) + "',";//
            }

            pos = pub::searchStr(mat_kind, "^", ui->cbb_mat_kind->currentText());
            sq += " kind_code = '" + pub::getStr(mat_kind, "^", pos + 1) + "',";// code '系统类别';

            pos = pub::searchStr(producer_codes, "^", ui->cbb_producer_code->currentText());
            sq += " factory_code = '" + pub::getStr(producer_codes, "^", pos + 1) + "',";//  producer_code '生产厂家';

            sq += " approve_info = '" + ui->le_approve_info->text().trimmed() + "',";// approve_info '批文信息';

        }
        else
        {
            sq += " valid_flag = '0',"; //
        }

        sq += " oper_code = '" + pub::usr_code + "',";// oper_code '操作员';
        sq += " oper_date = sysdate";// + oper_date '操作时间';

        sq += " where item_code = '" + ui->le_item_code->text() + "'";// item_code'物资项目编码';
        qDebug()<<"修改基础数据："<<sq;
    }
    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "保存失败！\n" + qro->lastError().text());
    }
    else
    {
        QMessageBox::warning(this, "注意", "保存成功！" );
        item_info_clear();
    }
}

void Form_yk_wzrk::on_cbb_producer_code_editTextChanged(const QString &arg1)
{
    return;

    if(timer_fac_changed->isActive())
    {
        timer_fac_changed->stop();
    }

    if(!initialFinished || arg1.isEmpty() || arg1.length() > 5)
    {
        qDebug()<<"initialFinished " << initialFinished << " arg1  "<< arg1;
        return;
    }

    timer_fac_changed->start(800);


}

void Form_yk_wzrk::timer_fac_changed_out()
{
    timer_fac_changed->stop();
    return;
    sq = "select company_name, company_code from mat_com_company where COMPANY_TYPE = '0' and VALID_FLAG = '1' ";
    sq += " and company_name like '%" + ui->cbb_producer_code->currentText().trimmed() + "%'";
    sq += " order by company_name";
    qDebug()<<"提取生产厂家："<<sq;
    //producer_code =
    pub::fillCombo(ui->cbb_producer_code, sq, -1, qrot);
}

void Form_yk_wzrk::generate_specs()
{
    QString pack, unit ;
    pack = ui->le_pack_qty->text() + ui->cbb_min_unit->currentText();
    unit = ui->cbb_pack_unit->currentText();
    if( pack.isEmpty() || unit.isEmpty())
    {
        return;
    }
    ui->le_specs->setText( pack + "/" + unit);
}

//void Form_yk_wzrk::on_le_base_dose_textChanged(const QString &arg1)
//{
//    if(is_new_drug)
//    {
//        generate_specs();
//    }
//}

//void Form_yk_wzrk::on_cbb_dose_unit_currentTextChanged(const QString &arg1)
//{
//    if(is_new_drug)
//    {
//        generate_specs();
//    }
//}

void Form_yk_wzrk::on_cbb_min_unit_currentTextChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    if(is_new_drug)
    {
        generate_specs();
    }
}

void Form_yk_wzrk::on_le_pack_qty_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    if(is_new_drug)
    {
        generate_specs();
    }
}

void Form_yk_wzrk::on_cbb_pack_unit_currentTextChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    if(is_new_drug)
    {
        generate_specs();
    }
}

void Form_yk_wzrk::on_le_item_name_textChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        ui->le_spell_code->setText(pub::pub::getFirstLetters(arg1));
    }
}


//void Form_yk_wzrk::on_le_id_code_returnPressed()
//{

//}

void Form_yk_wzrk::change_lock_status(QString type, bool status)
{
    //设置状态锁定或解除
    if(type == "in")
    {
        ui->cbbStoreDept->setEnabled(status);
        ui->cbbMode_r->setEnabled(status);
        ui->cbbCompany->setEnabled(status);

        if(status)
        {
            ui->pb_status_unlock_in->setEnabled(false);
            mdrs->setQuery(NULL);
        }
        else
        {
            ui->pb_status_unlock_in->setEnabled(true);

        }

    }
    else if(type == "out")
    {
        ui->cbbStoreDept->setEnabled(status);
        ui->cbbMode_c->setEnabled(status);
        ui->cbbReceiveDept->setEnabled(status);
        if(status)
        {
            ui->pb_unlock_status_out->setEnabled(false);
            mdcs->setQuery(NULL);
        }
        else
        {
            ui->pb_unlock_status_out->setEnabled(true);

        }
    }
}
void Form_yk_wzrk::on_pb_status_unlock_in_clicked()
{
    if(mdrd->rowCount()>0)
    {
        QMessageBox::StandardButtons bt;
        bt = QMessageBox::question(this, "注意", "录入项目数据未保存，是否清除然后继续？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
        mdrd->setQuery(NULL);
        qrm->exec("delete from tmp_mat_input");
    }
    change_lock_status("in", true);
}

void Form_yk_wzrk::on_pb_unlock_status_out_clicked()
{
    if(mdcd->rowCount()>0)
    {
        QMessageBox::StandardButtons bt;
        bt = QMessageBox::question(this, "注意", "录入项目数据未保存，是否清除然后继续？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
        mdcd->setQuery(NULL);
        qrm->exec("delete from tmp_mat_input");
    }
    change_lock_status("out", true);
}

void Form_yk_wzrk::dict_clicked()
{
    if(ui->rb_kind->isChecked())
    {
        ui->le_dict_type->setText(ui->rb_kind->text());
    }
    else if(ui->rb_unit_pack->isChecked())
    {
        ui->le_dict_type->setText(ui->rb_unit_pack->text());
    }
    else if(ui->rb_unit_min->isChecked())
    {
        ui->le_dict_type->setText(ui->rb_unit_min->text());
    }


    int width;

    QString valid = "'v'";

    if(ui->ckb_dict_inuse->isChecked())
    {
        valid += ",'1'";
    }

    if(ui->ckb_dict_unuse->isChecked())
    {
        valid += ",'0'";
    }

    if(ui->rb_kind->isChecked())
    {
        sq = " select KIND_CODE 编码, KIND_NAME 名称, "
             " VALID_FLAG 有效标志, ORDER_NO "
             " from mat_com_kindinfo "
             " where valid_flag in(" + valid + ")";

        if(ui->rbKey->isChecked())
        {
            sq += " order by KIND_NAME ";
        }
        else
        {
            sq += " order by KIND_CODE ";
        }
    }
    else if(ui->rb_unit_pack->isChecked())
    {
        sq = "select code 编码, name 名称, VALID_STATE 有效标志, sort_id"
             " from com_dictionary  "
             " where type ='MAT_PACK_UNIT' "
             " and valid_state in(" + valid + ")";

        if(ui->rbKey->isChecked())
        {
            sq += " order by name ";
        }
        else
        {
            sq += " order by code ";
        }
    }
    else if(ui->rb_unit_min->isChecked())
    {
        sq = "select code 编码, name 名称, VALID_STATE 有效标志, sort_id"
             " from com_dictionary  "
             " where type ='MAT_MINI_UNIT' "
             " and valid_state in(" + valid + ")";

        if(ui->rbKey->isChecked())
        {
            sq += " order by name ";
        }
        else
        {
            sq += " order by code ";
        }

    }

    qDebug()<<"display dict : "<<sq;

    md_dict->setQuery( sq, pub::db_o );
    width = ui->tv_dic_value->width();
    ui->tv_dic_value->setModel(md_dict);
    pub::setColumnWidth(ui->tv_dic_value, "0.25^0.3^0.25^0^0", width);

}

void Form_yk_wzrk::on_rb_kind_clicked()
{

    dict_clicked();
}

void Form_yk_wzrk::on_rb_unit_pack_clicked()
{

    dict_clicked();
}

void Form_yk_wzrk::on_rb_unit_min_clicked()
{

    dict_clicked();
}

void Form_yk_wzrk::on_tabWidget_currentChanged(int index)
{

    switch (index)
    {

    case 5:
    {
        dict_clicked();
        break;
    }
    }


}

void Form_yk_wzrk::on_tv_dic_value_clicked(const QModelIndex &index)
{
    ui->le_name->setText(index.siblingAtColumn(1).data().toString());
    ui->le_code->setText(index.siblingAtColumn(0).data().toString());
    ui->le_ord->setText(index.siblingAtColumn(3).data().toString());

    if(index.siblingAtColumn(2).data().toString() == "1")
    {
        ui->rb_inuse->setChecked(true);
    }
    else
    {
        ui->rb_unuse->setChecked(true);
    }
}

void Form_yk_wzrk::on_tv_dic_value_doubleClicked(const QModelIndex &index)
{
    on_tv_dic_value_clicked(index);
}

void Form_yk_wzrk::on_pb_save_dict_clicked()
{
    if(ui->le_name->text().trimmed().isEmpty()
            || ui->le_code->text().trimmed().isEmpty())
    {

        QMessageBox::information(this, "注意", "名称和代码不允许为空！");
        return;
    }
    QString name = ui->le_name->text().trimmed();
    QString code = ui->le_code->text().trimmed();

    QString valid;
    if(ui->rb_inuse->isChecked())
    {
        valid = "1";
    }
    else
    {
        valid = "0";
    }

    if(ui->rb_kind->isChecked())
    {
        mat_kind_manipulate(name, code, valid);
    }
    else if(ui->rb_unit_pack->isChecked())
    {
        com_dict_manipulate("MAT_PACK_UNIT", name, code, valid );
    }
    else if(ui->rb_unit_min->isChecked())
    {
        com_dict_manipulate("MAT_MINI_UNIT", name, code, valid );
    }
}

void Form_yk_wzrk::com_dict_manipulate(QString type, QString name,
                                      QString code,QString valid )
{
    sq = " select code from com_dictionary"
         " where type = '%1' and (code = '%2' or name = '%3')";
    sq = sq.arg(type)
            .arg(code)
            .arg(name);

    qro->exec(sq);

    if(qro->next())
    {
        //记录存在，进行修改
        sq = " update com_dictionary set "
             " name = '%1', "
             " sort_id = %2, "
             " valid_state = '%3',"
             " oper_code = '%4',"
             " oper_date = sysdate "
             " where "
             " TYPE = '%6'"
             " and code = '%5'";
        sq = sq.arg(name)
                .arg(ui->le_ord->text().trimmed().toInt())
                .arg(valid)
                .arg(pub::usr_code)
                .arg(code)
                .arg(type);

        qDebug()<<"库存物资字典变更："<<sq;
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "字典变更失败！\n"
                                     + qro->lastError().text());
            qDebug()<<qro->lastError().text();
            return;
        }
    }
    else
    {
        //记录不存在，插入新记录
        sq = "insert into com_dictionary "
             " (code, name, sort_id, "
             " valid_state,oper_code,oper_date,"
             " TYPE, PARENT_CODE, CURRENT_CODE, IS_COMMON, MARK, SPELL_CODE"
             " )values("
             " '%1','%2',%3,'%4','%5',sysdate,"
             " '%6', 'ROOT', 'ROOT', '1', 'true', '') ";
        sq = sq.arg(code)
                .arg(name)
                .arg(ui->le_ord->text().toInt())
                .arg(valid)
                .arg(pub::usr_code)
                .arg(type);

        qDebug()<<"插入新的库存物资字典"<<sq;
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "新建字典失败！\n"
                                     + qro->lastError().text());
            qDebug()<<qro->lastError().text();
            return;
        }
    }
}

void Form_yk_wzrk::on_pb_fresh_dict_clicked()
{
    dict_clicked();
}

void Form_yk_wzrk::mat_kind_manipulate( QString name, QString code,QString valid )
{
    sq = " select kind_code from mat_com_kindinfo"
         " where kind_code = '%1' or kind_name = '%2'";
    sq = sq.arg(code)
            .arg(name);

    qro->exec(sq);

    if(qro->next())
    {
        //记录存在，进行修改
        sq = " update mat_com_kindinfo set "
             " kind_name = '%1', "
             " order_no = %2, "
             " valid_flag = '%3',"
             " oper_code = '%4',"
             " oper_date = sysdate "
             " where "
             " kind_code = '%5'";
        sq = sq.arg(name)
                .arg(ui->le_ord->text().trimmed().toInt())
                .arg(valid)
                .arg(pub::usr_code)
                .arg(code);


        qDebug()<<"库存物资字典变更："<<sq;
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "字典变更失败！\n"
                                     + qro->lastError().text());
            qDebug()<<qro->lastError().text();
            return;
        }
    }
    else
    {
        //记录不存在，插入新记录

        //检索代码
        int pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
        QString dept_code = pub::getStr(store_depts, "^", pos);

        sq = "insert into mat_com_kindinfo "
             " (kind_code, kind_name, order_no, valid_flag,"
             " oper_code,oper_date,"
             " pre_code, storage_code, spell_code, effect_area,"
             " batch_flag, validdate_flag, account_code, account_name, finance_flag"
             " )values("
             " '%1','%2',%3,'%4','%5',sysdate,"
             " '0','%6', '-', '2', '0','0','', '','0') ";
        sq = sq.arg(code)
                .arg(name)
                .arg(ui->le_ord->text().toInt())
                .arg(valid)
                .arg(pub::usr_code)
                .arg(dept_code);

        qDebug()<<"插入新的库存物资字典"<<sq;
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "新建字典失败！\n"
                                     + qro->lastError().text());
            qDebug()<<qro->lastError().text();
            return;
        }
    }
}

void Form_yk_wzrk::on_cbbMode_c_currentTextChanged(const QString &arg1)
{
    if(!initialFinished)
    {
        return;
    }
    if(arg1 == "特殊出库")
    {
        ui->cbbReceiveDept->setCurrentText(ui->cbbStoreDept->currentText());
    }
}

void Form_yk_wzrk::search_checked(QString sour, QString dest)
{

    //可以自动录入的内容
    if(ui->cbbMode_r->currentText() == "一般入库")
    {
        //从入库验收表提取内容
        from_input_check(sour, dest);
    }

    showList();

}

void Form_yk_wzrk::from_input_check(QString sour, QString dest)
{

    sq = "select * from mat_com_input_check"
         " where drug_dept_code = '%1' and in_state = '0' "
         " and company_code = '%2' and valid_flag = '1' and check_result = '1'";
    sq = sq.arg(dest).arg(sour);

    qDebug()<<"检索已经验收的入库记录："<<sq<<"\n";
    qro->exec(sq);

    if(!qro->next())
    {
        QMessageBox::information(this, "注意", "找不到指定条件的验收记录！");
        return;
    }

    while(true)
    {
        //入库数据插入临时表

        sq = "replace into tmp_mat_input ("
             "item_code, item_name, company_code, company_name, specs, approve_info, ";  //药品编码,品名,生产商,规格,批准文号
        sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,药品中药西药类别
        sq += "drug_quality, sale_price, in_price,";   //药品普药特药类别，零售价格,采购价格
        sq += "med_list_codg,"; //医保码
        sq += "batch_no, produce_date, valid_date, num,";   //批号,生产日期,效期,数量
        sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost ,";   //发票号, 发票日期, 备注， 购入金额，零售金额
        sq += "out_bill_code, out_list_code, out_serial_code, input_check_no, stock_no ";//
        sq += ") values(";
        sq += "'" + qro->value("drug_code").toString() + "',";//药品编码
        sq += "'" + qro->value("trade_name").toString() + "',";//品名
        sq += "'" + qro->value("producer_code").toString() + "',";//生产商

        qrot->exec("select company_name from mat_com_company "
                   " where company_code = '"
                   + qro->value("producer_code").toString()
                   + "' and company_type = '0'");
        qrot->next();
        sq += "'" + qrot->value("company_name").toString() + "',";//生产商"

        sq += "'" + qro->value("specs").toString() + "',";//规格
        sq += "'" + qro->value("approve_no").toString() + "',";//批准文号
        sq += "'" + qro->value("pack_qty").toString() + "',";//包装数量
        sq += "'" + qro->value("pack_unit").toString() + "',";//包装单位
        sq += "'" + qro->value("drug_type").toString() + "',";//药品类别，中药，西药
        sq += "'" + qro->value("drug_quality").toString() + "',";//药品类别，普药，特药
        sq += "'" + qro->value("retail_price").toString() + "',";//零售价格
        sq += "'" + qro->value("purchase_price").toString() + "',";//采购价格
        sq += "'" + qro->value("med_list_codg").toString() + "',";//医保码
        sq += "'" + qro->value("batch_no").toString() + "',";//批号
        sq += "'" + qro->value("manu_date").toDate().toString("yyyy-MM-dd") + "',";//生产日期
        sq += "'" + qro->value("valid_date").toDate().toString("yyyy-MM-dd") + "',";//效期
        //sq += QString::number(qro->value("apply_num").toInt() *  qro->value("pack_qty").toInt()) + ",";//数量
        sq += "'" + qro->value("apply_num").toString() + "',";//数量
        sq += "'',";//发票号" + ui->leFph->text().trimmed() + "
        sq += "'0001-01-01',";//发票日期" + ui->leFprq->text().trimmed() + "
        sq += "'" + qro->value("mark").toString() + "',";//备注
        sq += "'" + qro->value("min_unit").toString() + "',";//" + item_detail["min_unit"] + "
        sq += qro->value("apply_num").toString() +
                "*" + qro->value("purchase_price").toString() +
                "/" + qro->value("pack_qty").toString()+ ",";//购入金额
        sq += qro->value("apply_num").toString() +
                "*" + qro->value("retail_price").toString() +
                "/" + qro->value("pack_qty").toString()+ ",";//零售金额
        sq += "'0',";//
        sq += "'',";//
        sq += "'0',";//
        sq += "'" + qro->value("input_check_no").toString() + "',";//验收记录流水号
        sq += "'0'";//
        sq += ")";

        qDebug()<<"insert data to temporary table : "<< sq;

        if(!qrm->exec(sq))
        {
            QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
            return ;
        }

        if(!qro->next())
        {
            break;
        }
    }
}
